I want to split the string into integers and operators for doing Infix expression evaluation in python.
Here is my string:
JavaScript
x
2
1
>>> s = (1-2+3)*5+10/2
2
I tried this to split:
JavaScript
1
3
1
>>>list(s)
2
['(', '1', '-', '2', '+', '3', ')', '*', '5', '+', '1', '0', '/', '2']
3
This is wrong. Since ’10’ is splitted into ‘1’,’0′
I tried alternative:
JavaScript
1
3
1
>>> re.findall('[+-/*//()]+|d+',s)
2
['(', '1', '-', '2', '+', '3', ')*', '5', '+', '10', '/', '2']
3
This is also went wrong. Since ‘)*’ should be splitted into ‘)’, ‘*’
Could you help to split the operators and integers from the given expression?
Advertisement
Answer
This is not the best solution for infix. Remove the + after [] like:
JavaScript
1
6
1
import re
2
s = "(1-2+3)*5+10/2"
3
print re.findall('[+-/*//()]|d+',s)
4
5
['(', '1', '-', '2', '+', '3', ')', '*', '5', '+', '10', '/', '2']
6
Try the following link for correct solution: Simple Balanced Parentheses
JavaScript
1
28
28
1
from pythonds.basic.stack import Stack
2
3
def postfixEval(postfixExpr):
4
operandStack = Stack()
5
tokenList = postfixExpr.split()
6
7
for token in tokenList:
8
if token in "0123456789":
9
operandStack.push(int(token))
10
else:
11
operand2 = operandStack.pop()
12
operand1 = operandStack.pop()
13
result = doMath(token,operand1,operand2)
14
operandStack.push(result)
15
return operandStack.pop()
16
17
def doMath(op, op1, op2):
18
if op == "*":
19
return op1 * op2
20
elif op == "/":
21
return op1 / op2
22
elif op == "+":
23
return op1 + op2
24
else:
25
return op1 - op2
26
27
print(postfixEval('7 8 + 3 2 + /'))
28
Keep in mind that this is a postfix implementation and its just for example. Do the infix by yourself and if you have any difficulties just ask.