Python: I'm misunderstanding stack logic, but I'm not sure where -
i have function evaluating infix expression via use of stacks. (bet you've never seen 1 before.) takes expression in list format, wherein each item in list single character (operand, operator, or parenthesis.)
s = stack() tempvar = none ops = ['+','-','/','*'] in expression: if == '(' s.push(i) elif i.isdigit(): if tempvar none: tempvar = else: tempvar = tempvar + elif in ops: if tempvar not none: s.push(tempvar) tempvar = none popped = str(s.pop() + str(s.pop()) last = s.pop() if last not ')': popped += str(last) x in popped: print 'popping',x,'from stack.' print 'popping',last,'from stack.' math = eval(popped) s.push(math) print 'pushing',math,'back onto stack.
my intention using "tempvar" string that, since i'm iterating on expression character character, encounter issue multi-digit numbers. i'm making string out of them , pushing string onto stack instead.
i having 2 problems this, , i'm not sure why i'm getting 1 of them.
for input
((21*2)-(4/2))
i output
pushing ( onto stack pushing ( onto stack pushing 21 onto stack pushing * onto stack pushing 2 onto stack popping 2 stack **popping * stack popping 2 stack popping 1 stack popping 21 stack**
i've set off problem portion asterisks. understanding of stacks function last-in-first-out, , don't care sitting on top, pop takes off. 21 first thing pushed onto stack, looks it's getting read individually (as 21, last entry pop off) , split in half '2' , '1'- expect 1 pop off before 2! misunderstanding either stacks, or i've written?
for x in popped: print 'popping',x,'from stack.'
popped
string, loop iterate on 1 character @ time.
Comments
Post a Comment