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.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
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.
Closed 1 year ago.
Improve this question
V=str(input ('\n\tEnter\n\n\t'))
if V.isnumeric:
print (f'\n\tYour V is a numeric and it is "{V}"\n\t')
When I enter an alphabet, it considers it as a numeric. How to make it only accept numbers or alphabets?
isnumeric is a function but you are not calling it so it is returning true as it is a defined function. Your if statement is checking whether isnumeric is defined for the variable V
You should do this -
V=str(input ('\n\tEnter\n\n\t'))
if V.isnumeric():
print (f'\n\tYour V is a numeric and it is "{V}"\n\t')
I think it should be V.isnumeric() there is some limitations on negative
Definition and Usage
The isnumeric() method returns True if all the characters are numeric (0-9), otherwise False.
Exponents, like ² and ¾ are also considered to be numeric values.
"-1" and "1.5" are NOT considered numeric values, because all the characters in the string must be numeric, and the - and the . are not.
This should be useful if you want to try a couple of functions: https://lerner.co.il/2019/02/17/pythons-str-isdigit-vs-str-isnumeric/
The function isnumeric() is not being called in your code presently, you are simply referencing it:
if v.isnumeric: # This resolves to a pointer to the isnumeric function
....
To call a function, you require v.isnumeric(). Note that in the original (without parentheses) it resolves to function object, which in turn evaluates to True (essentially, because it exists at all) when in an if clause. However, the function itself is never run. It's for this reason that you're seeing it print out every time.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
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.
Closed 8 years ago.
Improve this question
I am using Python 3.1 IDLE and have found that the space (which I will mark out as such - _) is being highlighted by IDLE as a syntax error. I would like to know if anyone knows what the problem is and offer a solution. I know it looks wrong, but the underscore is just there to highlight where IDLE says the problem is. I can't work out what the issue with that line and the next line is.
def attrSelection():
while attrChoice!=6
if attrChoice==1:
attrChoice=Power
baseAttr=int(basePow)
attrEditor()
_ elif attrChoice==2:
attrChoice=Health
baseAttr=int(baseHlth)
attrEditor()
elif attrChoice==3
attrChoice=Wisdom
baseAttr=int(baseWis)
attrEditor()
elif attrChoice==4:
attrChoice=Dexterity
baseAttr=int(baseDex)
attrEditor()
elif attrChoice==5:
assignRandom()
else:
print('Option does not exist. Please enter option in range 1-6.')
attrChoice=input('Choice: ')
The IDE may points you to the errors here:
def attrSelection():
while attrChoice!=6
...
elif attrChoice==3
...
You are missing : after the 6 and 3. Otherwise, everything looks fine, assuming you didn't also missed the indentation at the beginning as you are listing the code.
python is really picky about spaces, because it uses spaces for defining code blocks. That's a design choice, it's radical, and has its proponent and opponent. But as a consequence, you need to be really careful in how many spaces you put in front of a line of code, because python will not understand something like:
i = 1
j = 2
k = 3
as logically, it would mean that i, j and k are not in the same blocks, which is impossible as a block shall begin with special statements, usually ending with a colon (:). So python will just throw the same syntax error you've seen in your code saying that there's a problem with spaces!
In your case, it's likely you're using tabs for alignment, which makes two characters to get something aligned at column 8. But somewhere in your code, you had spaces instead of tabs, making it 5 characters to have your code aligned at column 8
<TAB><TAB>i = 1
<TAB> j = 2
so if you consider tabs as spaces, here's what gets written:
i = 1
j = 2
thus python not understanding your code! As a general advice, only use spaces never tabs to indent your code, so you can't be tricked by tab/spaces mess up.
N.B.: as the others are telling, your code is indeed being wrong, missing colons at the end of the following statements:
while attrChoice!=6
...
elif attrChoice==3
...
as they pointed that out, I did not place it in my answer until now. Though if your IDE is giving you an error in the indentation, whereas it's a missing colon, then you should consider changing IDE, as your IDE is really failing at giving relevant errors/warnings that can help code faster and more easily.
There are colons missing after the while and second elif. It scanned fine in idle for me after adding those.
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 8 years ago.
Improve this question
I am trying to program a calculator which allows users to input an equation and receive an answer (order of operations apply). I will not be using the input() command to gather user input, but rather the raw_input() command. I heard from another user that I could accomplish this task with the help of recursive parsing, I quote:
"The first step would be separating the string into each argument.
Let's say that the user inputs:
1+2.0+3+4
Before you can even convert to ints, you are going to need to split the string up into its components:
1
+
2.0
+
3
+
4
This will require a recursive parser..." -aong152
Additionally, I read this article which explains how recursive parsing might be used to produce the results I am looking for:
http://blog.erezsh.com/how-to-write-a-calculator-in-70-python-lines-by-writing-a-recursive-descent-parser/
I do not understand the coding that the author uses, and I have searched on this website and on Google for help in beginning to learn recursive parsing, but I cannot find anything. Can anyone give me a push in the right direction and explain the basics of recursive parsing to me?
Recursive parsing of simple arithmetic summations can be fairly easily analogized into adding a lot of brackets. A recursive parser might parse the above summation like this: 1+(2.0+(3+(4))). The reason for this is that you want to break the whole thing down into individual units of work that can be computed. This means each part must contain at most two numbers and one operator (the base case for the recursion would be a single number).
Each pair of brackets is added by an additional level of recursion (the function calling itself). So, the initial call sees something like "1 plus some complex stuff the next level of recursion will take care of for me".
When the base case is not yet reached, each call will parse the first number and the operation. Then, it will call itself on the next part of the string after the operation, and return the results of the operator for its digit and that next call (eg. something like return number + parse(string[length:])).
When the base case is reached (only one number is left in the string), instead of returning something depending on another function call, it will just return the number. Then, the recursion unwinds, with each function getting the value of the complex right hand side. Eventually, the original call will return the result.
This is fairly easily extended to allow for other operators by having each instance of the function work on an operator (instead of an operator and a number), and the expression to the left and right of it, starting with the highest-precedence operator. So, when parsing a string like 0+1+2*3+4, you must start with the multiplication. Your function, returning something like function(left-hand-side) operator function(right-hand-side), would initially parse it like this: (0+1+2)*(3+4). This would turn into (0+(1+(2)))*(3+(4)). You can parse linearly along operators with the same precedence, so the algorithm can iterate looking for multiplication or division to recurse on, recursing on the first one found; if none is found it can do the same for addition and subtraction, and finally if none is found just return the number as the base case (interestingly, the latter example I gave has 2 base case instances, 2 and 4; this is a feature of multiple recursion).
A fully working parser using pyparsing that can handle +-/* can be found here:
http://pyparsing.wikispaces.com/file/view/fourFn.py/30154950/fourFn.py
This uses a recursive grammar to handle the proper nesting of parenthesis. It may be worth working through the examples in the book, you'll learn to write a grammar and how it's something different from a parser!