Data Structures & AlgorithmsHardTCS Digital · Infosys SP
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+9*1-3+6"))- A. 19
- B. −67
- C. 5
- D. 17
Correct answer: D. 17
Before pushing an operator, apply every stacked operator of greater OR EQUAL precedence (that makes − left-associative). Result: 17.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- Swap every two adjacent nodes of a linked list by relinking (not by swapping values). What is printed? python def swappairs(h): d = p =…
- How many pairs (i < j) of [2, 15, 17, 10, 24, 2, 10, 2, 4, 9] have a[i] + a[j] divisible by 4? (Count remainders mod 4 and pair r with 4 −…
- A 2-D array A[0..11][0..29] of 2-byte elements is stored in column-major order starting at address 2000. What is the address of A[9][6]?
- For each day, a monotonic stack finds how many days you must wait for a strictly warmer temperature (0 if never). What is printed? python…
- Longest run of consecutive integers (in any order) using a hash set and starting only from numbers whose predecessor is absent. What is…
- Quickselect returns the k-th smallest element of an unsorted array in expected O(n) time. For [29, 18, 10, 32, 39, 19, 36, 13] and k = 4…