Data Structures & AlgorithmsHardFlipkart/Uber OA · placement

Evaluate an infix expression of single digits with two stacks (operands and operators, usual precedence, left-associative). What is printed?

Evaluate an infix expression of single digits with two stacks (operands and operators, usual precedence, left-associative). What is printed?
def ev(s):
    nums, ops = [], []
    prec = {"+": 1, "-": 1, "*": 2, "/": 2}
    def apply():
        b, a, o = nums.pop(), nums.pop(), ops.pop()
        nums.append(a + b if o == "+" else a - b if o == "-" else a * b if o == "*" else a // b)
    for ch in s:
        if ch.isdigit(): nums.append(int(ch))
        else:
            while ops and prec[ops[-1]] >= prec[ch]: apply()
            ops.append(ch)
    while ops: apply()
    return nums[0]
print(ev("5*3-8+1+9"))
  1. A. −3
  2. B. −75
  3. C. 17
  4. D. 18

Correct answer: C. 17

Before pushing an operator, apply every stacked operator of greater OR EQUAL precedence (that makes − left-associative). Result: 17.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic