world!, I ran into a problem earlier today… I am trying to split operations apart from digits and variables. it’ll split +,-,/,* apart from the digits or the variable (ex: 10+11+10 goes in the code and a list comes out with ["10","+","11","+","10"])
My code:
x = "100+20+a"
operators = ["*","/","+","-"]
def get_index_of(OP,txt):
return [v for v,i in enumerate(txt+"+") if i == OP]
l = []
for i in operators:
l.append(get_index_of(i,x))
spliting = sum(l,[])
out = []
for j in spliting:
out.append(x)
x = x[:j]
print(out)
The output I get:
['100+20+a', '100', '100']
The output I want:
["100","+","20","+","a"]
>Solution :
Using stack
def parse(expression, operators = ["*","/","+","-"]):
stack = [''] # start with empty string on stack
for c in expression:
if c in operators:
stack.append(c) # place operator as new element on stack
stack.append('')
elif c != " ": # not a space
stack[-1] += c # append to last element on stack
return stack
Example
print(parse("100+20+a"))
# Output: ['100', '+', '20', '+', 'a']