python - Stack, Pop and Add -
this calculate
function should work
calculate((1, 2, '+', 3, '*')) return 9 1. take 1, push 1 # stack [1] 2. take 2, push 2 #stack [1, 2] 3. take '+', pop 2, pop 1, calculate 1+2 = 3, push 3 #stack [3] 4. take 3, push 3 #stack [3, 3] 5. take '*', pop 3, pop 3, calculate 3 * 3 = 9, push 9 #stack [9] 6. input empty, pop 9, return 9
i don't know how use string '+' here add 1 , 2 together. seems impossible.
here code. suppose convert tuple , put list pop first 2 number out combine binary operators '+', '-', '*', '/'
def calculate(inputs): #(1, 2, '+', 3, '/') if len(inputs) <= 1: return inputs[0] in range(len(inputs)+1): ## (0,...5) s = make_empty_stack() # [] first = push_stack(s, inputs[i]) #[1] # push_stack pushes item onto stack s, returns stack second = push_stack(s, inputs[i + 1]) ##[2,1] third = push_stack(s, inputs[i +2]) ##[2,1,+] f = pop_stack(third) #removes top item of stack #2
here test cases
calculate((1, 2, '+', 3, '*')) ## 1+2 * 3 calculate((1, 2, '+', 3, '/')) ## (1 +2) / 3 = 1 calculate((28,)) # 28 calculate((1, 2, '*', 3, '-', 2, '*', 5, '+')) ## ((1*2) - 3) * 2)+5 = 3
the operator
module provides convenient functions python operators, including +
, *
:
import operator ops = {'+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.floordiv}
now can use ops
dictionary implement operations on stack:
def calculate(inputs): if not inputs: return s = make_empty_stack() item in inputs: if item in ops: op2, op1 = pop_stack(s), pop_stack(s) res = ops[item](op1, op2) push_stack(s, res) else: push_stack(s, item) return pop_stack(s)
the code pops 2 items stack , passes them operator function, provided item
valid operator. need invert operands, however; want subtract top-most stack item second item on stack, not other way around. else pushed stack instead.
note need create empty stack once, outside loop.
Comments
Post a Comment