How To Split The Integers And Operators Characters From String In Python?
I want to split the string into integers and operators for doing Infix expression evaluation in python. Here is my string: >>> s = (1-2+3)*5+10/2 I tried this to split: &
Solution 1:
This is not the best solution for infix. Remove the + after [] like:
import re
s = "(1-2+3)*5+10/2"print re.findall('[+-/*//()]|\d+',s)
['(', '1', '-', '2', '+', '3', ')', '*', '5', '+', '10', '/', '2']
Try the following link for correct solution: Simple Balanced Parentheses
from pythonds.basic.stack import Stack
defpostfixEval(postfixExpr):
operandStack = Stack()
tokenList = postfixExpr.split()
for token in tokenList:
if token in"0123456789":
operandStack.push(int(token))
else:
operand2 = operandStack.pop()
operand1 = operandStack.pop()
result = doMath(token,operand1,operand2)
operandStack.push(result)
return operandStack.pop()
defdoMath(op, op1, op2):
if op == "*":
return op1 * op2
elif op == "/":
return op1 / op2
elif op == "+":
return op1 + op2
else:
return op1 - op2
print(postfixEval('7 8 + 3 2 + /'))
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.
Solution 2:
Try
re.findall('[+-/*//()]|\d+',s)
You don't need the +
, since you only want to have one special sign.
Solution 3:
Using split:
printfilter(lambda x: x, re.split(r'([-+*/()])|\s+', s))
Solution 4:
If you can avoid regular expressions, you can try an iterative solution (just a rough code):
s = "(1-2+3)*5+10/2"
numbers = "0123456789."
def split_operators(s):
l = []
last_number = ""for c in s:
if c in numbers:
last_number += c
else:
if last_number:
l.append(last_number)
last_number = ""if c:
l.append(c)
if last_number:
l.append(last_number)
return l
print split_operators(s)
result:
['(', '1', '-', '2', '+', '3', ')', '*', '5', '+', '10', '/', '2']
Post a Comment for "How To Split The Integers And Operators Characters From String In Python?"