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 :)
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I would like to convert birnary to in using own algorithm.
Here is the code:
binary=""
decimal=""
while binary!="exit":
decimal= input(">>")
decimal = decimal
if decimal!="0":
n = len(decimal) -1
n = pow(n, 2)
print(n)
Input:
1010
Bad Output:
9
When I enter binary and check them with calculator they arent true.
I dont have big clue how to make it so sorry for mistakes in code.
Thanks for reply
You need to move the input (where the user enters a binary number) outside the loop that's processing it. Then you have string containing ones (1) and zeros (0) which you can loop through.
Starting at the right-hand end of the string, multiply that number (1 or 0) by 1 (let's call this multiplier the ordinal) and save the result as total.
Multiply the ordinal by 2.
Grab the next number (from the right) from the input string and multiply it by the ordinal, add the result to total.
Keep going, multiplying the ordinal and using that to multiply the next number from the input string, until you run out of "numbers" in the input string.
Print total
First off, I think the line n = pow(n, 2) might be backwards from what you need. If you're converting binary digits, 2 is the base and n will be the power to raise it to, so you'll need n = pow(2, n).
Now, since you want to add up all the digits that are set to 1, you'll also need to add them to a new variable too. If you have more questions about this just ask here, and I'll see how I can help :)
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.
Closed 9 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.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I have a data set as follows it includes some negative values. I have written codes to read those values. But when any negative numbers percent. It gives error. File format is as below
1SOL HW1 2 1.4788 2.7853 -0.7702
1SOL HW2 3 1.4640 -2.8230 0.6243
2SOL OW 4 -1.5210 0.9510 -2.2050
2SOL HW1 5 1.5960 -0.9780 2.1520
I have written code as follow. I am using for loop and if function to select P[3], P[4], P[5] positions.
X=[]
P = line.split()
x = float(P[3]) `#then I collect these numbers in to array like X = []`
X.append(x)
This code work if there is no negative values.
Then I used following function to write X in to another file. But it is not working
A.write('%s\n' % (X)) `# this is not working since it X is Float. File open as A to write`
Please some one help me to correct my cords.
The reason A.write('%s\n' % (X)) doesn't work has nothing to do with X being a float.
There may be a problem in that (X) isn't a tuple of one float as you seem to expect, it's just a float. Commas make a tuple, not parentheses. In particular, comma-separated values anywhere that they don't have some other meaning (function arguments, list members, etc.) are a tuple. The parentheses are only there to disambiguate a tuple when the comma-separated values would otherwise have another meaning. This is usually simple and intuitive, but it means that in the case of a one-element tuple, you need to write (X,).
However, even that shouldn't be a problem: '%s\n' % 3.2 is '3.2\n'.
On top of that, X isn't actually a float in the first place, it's a list. You explicitly created it as X = [], and then appended each float to it. Again, that's not a problem, but it means you're possibly not getting the output you wanted. This is just a guess, since you never explained what output you wanted or what you were actually getting. But '%s\n' % [3.2, 3.4] is '[3.2, 3.4]\n'. If you wanted each one on a separate line, you have to loop over them, explicitly or implicitly—maybe ''.join('%s\n' % x for x in X).
As for why your negative numbers don't work, there are many possibilities, and it's impossible to guess which without more information, but here are some examples:
There is something that Python (more specifically, split()) considers whitespace, even if it doesn't look like it to you, between the - and the numbers. So, you're trying to convert "-" to a float rather than "-12345".
Those apparent - characters are actually a Unicode minus rather than a hyphen, or something else that looks similar. .decode-ing the file with the right encoding might solve it, but it might not be enough.
There are invisible, non-spacing characters between the - and the first digit. Maybe Unicode again, or maybe just a control character.
In many cases, the exception string (which you didn't show us) will show the repr of the string, which may reveal this information. If not, you can print repr(P[3]) explicitly. If that still doesn't help, try print binascii.hexlify(P[3]) (you'll have to import binascii first, of course).
It's impossible to tell what will work because we can't see your source file, but the problem you're having is with your split function. If I were you, I'd try P = line.split('\t') and see if that resolves your issue.
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 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.