I am quite new to programming. This is in relation to python. So the idea is to take an expression such as 3/5 or, at most, 3/5*2(at most two operators, note that the operators can be any of +,-,/,*) and solve it. White space can exist anywhere within the expression.
The user enters the expression, say 3/5, and the program needs to solve the expression and display the answers. What I have tried is below. Note, I only have attempted the first part, once I can properly split the original expression that the user enters(which would be a string), creating functions would be the easy part:
expres= str(input("something:"))
ssplit= hit.partition("/")
onec= int((ssplit[0].lstrip()).rstrip())
twoc= (ssplit[1].lstrip()).rstrip()
threec= int((huns[2].lstrip()).rstrip())
print(onec,"...",twoc,"...",threec) #just a debug test print
So above, I can take an expression like 3/5 and split it into three separate strings:3 , /, and 5. I can also remove all whitespace before and after the operators/operands. I am having problems with splitting expressions like 4/5+6, Because I can't put code in for ssplit[3] or ssplit[4] and then enter an expression like 3/5, because it won't be defined. Basically I needed you help to find out how to split an expression like 3/4-6,etc. I also need help with the line "ssplit= hit.partition("/")
" so that it will look at the entered expression and work with +,-, and * as well. Any and all help is appreciated. Also if my code above looks nasty and inefficient please give me criticism. Thanks!
Note I can't, and wouldn't want to use eval. Order of operations is required. I cant use complicated commands. I need to keep it simple, the most I can use is string libraries, converting between strings/integers/floats etc. and if,and,etc. statements. I can also use functions.
str(input(...))
. If you're on py3k, the output is already a string. If you're on py2k, then you should useraw_input
. – Allegeeval(raw_input())
:P – Gareri2+3*2
-- If you parse from left to right, you'll get 12, if you parse using order of operations, you'll get 8 ... – Allegeast.literal_eval
doesn't handle any sort of operators -- e.g.:ast.literal_eval('1+3')
fails. – Allegeeval
can do. Even with that there are some lesser known issues, but they can be worked around if you're careful and know what you're doing. That said, It's probably best to avoid if you're not certain that you know what you're doing. – Allege