Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How to convert number such as 24 to the two words "two", "four".
Quick way I thought of.
First you need a way to loop through the integer. You can try doing some weird diving by 10 and using the modulus of it... or just convert it to a string.
Then you can iterate through each 'number' in the string and use a simple lookup table to print out each number.
numberconverterlookup={'1':'one'
'2':'two'
'3':'three'
'4':'four'
'5':'five'
'6':'six'
'7':'seven'
'8':'eight'
'9':'nine'
'0':'zero'
}
number = 24
stringnumber = str(number)
for eachdigit in stringnumber:
print numberconverterlookup[eachdigit]
Note this only handles single digits and can't easily handle large numbers. Otherwise you'd have to write out each number in the lookup table by hand. That is very cumbersome.
Some key concepts are illustrated here:
Dictionary: This maps a 'key' to a 'value'. I.e. '1' maps to 'one'
For loop: This allows us to go through each digit in the number. In the case of 24, it will loop twice, once with eachdigit set to '2', and loops around again with eachdigit set to '4'. We cant loop through an integer because it is itself a single entity.
Typecasting: This converts the integer type 24 into a string '24'. A string is basically a list of individual characters grouped together, whereas an integer is a single entity.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have a list as below:
a=[0,0,2,4,4,6,6,9,12,13,13,16,16,21,21,24,26,26,28,28,31,34,34,37,37]
The list satisfies:
1.sorted in ascending order
2.each number occurs 1-2 times
How to count all AABB-like occurrence in the list?
In the above example the answer should be 5
(4,4,6,6) (13,13,16,16) (16,16,21,21) (26,26,28,28) (34,34,37,37)
There are many ways to do this. The simplest I could think of is using 'enumerate' and list comprehension with a condition to test for 'aabb' patterns.
result = len([x for idx,x in enumerate(a) if idx<len(a)-3 and x == a[idx+1] and x!=a[idx+2] and a[idx+2] == a[idx+3]])
The idx < len(a) - 3 avoids index problems.
Although it may not seem that way at first (because you are processing a list of ints) this is actually an example of a string searching algorithm.
If you look at the wikipedia article (linked to above) you will see that there are quite a few uses for such algorithms, beyond simply searching strings, one major one being searching DNA sequences for a given pattern, so it is quite an important area of computer science.
As well as multiple uses there are multiple implementations so you could approach this several ways.
The naive approach is to simple iterate through the list and check to see if the next element matches the current element and then if the following elements also match. The problem here is that you have to go through the whole list and then iterate through each sublist to check if it matches the given pattern. In big O notation we say this approach has a complexity of O(nm) where n is the length of the list and m is the length of the pattern you are searching, so it is not very efficient.
There are many ways to improve on the naive approach, and there may even be some that are unknown. I'll leave that to you to figure out, but hope this gives you some pointers.
Just loop through - and compare the pairs
a=[0,0,2,4,4,6,6,9,12,13,13,16,16,21,21,24,26,26,28,28,31,34,34,37,37]
for i in range(len(a)-3):
if (a[i]==a[i+1] and a[i+2]==a[i+3]):
print(str(a[i])+str(a[i+1])+str(a[i+2])+str(a[i+3]))
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
In the following code snippet for text summary, it is intended to store an integer/importance value corresponding to each sentence in a paragraph.I tried using dictionary , but have issues with similar indices Is there a data structure in python that can make use of a string as an index where single string may occur multiple times?
line = fr.readline()
relevance = {}
while line:
line_value = select(line)
relevance[line] = line_value #error in this line
line = fr.readline()
The best data structure depends on what you then need to do with it.
A dictionary might work. However:
standard dictionaries are unordered
duplicate strings might need special handling.
If neither is a problem, simply change [] to {} in your code.
Another alternative is to have a list of (line,value) tuples. This will preserve the ordering of data and duplicates, but will not offer efficient string-based lookups.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I have a number which I want to split into smaller numbers of equal length.
Suppose, I have the number 212313454
I, now want to split it into 3 numbers of 3 digits each:
212, 313 and 454
What if I want to randomly split it? I mean
212313454 into
213, 354, 114
Is there any way to do this?
You can use modulus operator % and division operator / and form the divisor as 10^n where n is number of digits in each result of split.
Convert them to a string and then split them. Like:
s = str(212313454)
a = s[0:3]
b = s[3:6]
c = s[6:]
Use a loop for a variable length number.
I'm sorry to ask but your question is vague (yes I know people have "answered" the question...).
"split [a number] into smaller numbers of equal length". Your example and hence everyone's answers assume you just have 9 decimal digits and want three smaller integers back, but what if you have a longer or shorter number, or want more/less subdivisions?
and randomly splitting "212313454 into 213, 354, 114". What is the correlation of these smaller numbers with the larger # exactly? 213 isn't in 212313454 if my eyes are working properly. If you want to pick random digits from an integer you can do that.
Lastly if you are just experimenting for fun, cool, but you should think a bit about making integers into strings and back and forth. A lot of math routines in python you should checkout are in the standard library, e.g. math module, random module, and bitwise operators too.
Im not going to write the code for you but here is a simple way to do it:
Make the int a string
split the string each 3 characters
once you do that iterate the list and turn the strings back into ints
I think you can figure it out if you try!
Good luck :)
The easiest way to convert the integer to a string adn then change it back to int again...
Here is how I would do...
Code:
c = 212313454
def splits(c,length):
l = [c[i:i+3] for i in range(0,len(c),3)]
print map(int,l)
if __name__=='__main__':
splits(str(c),3)
Output:
[212, 313, 454]
Hope this helps :)
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
the following problem in python please .....
Assuming that s is a string of lower case characters.
how would I write a program that prints the number of times the string 'bob' occurs in s. For example, if s = 'azcbobobegghakl', then my program would print
'Number of times bob occurs is: 2'
I am a completely new to python and appreciate any help
If you didn't want to count overlapping bobs as separate values, this would be easy:
s.count('bob')
But you apparently do. (I had to guess that, based on the fact that your intended output is 2 rather than 1… in the future, it would be better to explain your problem instead of leaving it ambiguous.) As the help says, count returns "the number of non-overlapping occurrences of substring sub…", so that won't do any good.
So, for that, you will have to do it manually. I'll show an example that should have enough to get you started:
for i in range(len(s)):
if s[i:].startswith('bob'):
print('Found a bob')
A slightly smarter way to do this would be to use the find method on strings. You can find details on this in the online docs, or by typing help(str.find) in the interactive console. Notice that find takes a start argument. You should be able to figure out how this would help you; it may take a bit of work to get the details right, but if you get stuck, you can always post a new question asking for specific help.
You can try this way
string = "BOBOBOBOBOABCDE"
search = "BOB"
print len([i for i in range(len(string)) if string.startswith(search, i)])
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am using python to do some text comparison. The text format is like 44=100. Let's say, I have 2 text, 44=100 and 44=3001. I call the string on the left of = is tag, right is value. Now I need to compare the tag and value for them. The tag must be the same, 44 equals 44, but the values don't have to, as long as its format is the same. ie. 100 and 3001 are in the same format(normal digits). But 1.0E+7 in 44=1.0E+7 is different. tThe point is on value comparison. ie. I write a script comp.py, when I run comp.py 2000 30010, I will get output true; while I run comp.py 100000 1.0E+8, output is false. How can I do it? I am thinking about converting the value into an regular expression and comparing it with other.
pseudo code:
rex1 = '100000'.getRegrex(), rex2 = '1.0E+8'.getRegrex(), rex1.compare(rex2)
Is it a feasible way? any advice?
rex1 = '100000'.getRegrex(), rex2 = '1.0E+8'.getRegrex(), rex1.compare(rex2)
Your approach is wrong. It is not only difficult but also illogical to "deduce" a regexp from a given string. What you would do is:
Define your types. With each type you would have a corresponding regexp.
Compare your input text against all your defined types and check which type it is of.
Compare the two types.
Actually, your idea of rex1 = '100000'.getRegrex() could be done
rex1 = re.compile('10000')
But as Thustmaster pointed out, you may want to define the regular expression with more abstraction of the pattern of your data.