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("7*3*2-8+6"))- A. −252
- B. 41
- C. 28
- D. 40
Correct answer: D. 40
Before pushing an operator, apply every stacked operator of greater OR EQUAL precedence (that makes − left-associative). Result: 40.
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
- One Lomuto partition (pivot = LAST element; i marks the end of the 'less than pivot' region; when a[j] < pivot, increment i and swap a[i]…
- Insertion sort (ascending; shift larger elements right, one key comparison per inner-loop test, the loop stops at the first element ≤ the…
- One Hoare partition with the FIRST element as pivot (i moves right while a[i] < pivot, j moves left while a[j] > pivot, swap while i < j…
- How many inversions (pairs i < j with a[i] > a[j]) does [5, 6, 10, 37, 38, 4, 17, 23] have? (This is also the number of swaps bubble sort…
- Keys 112, 95, 54, 144, 21, 31, 32 are inserted in this order into an empty table of size 11 by double hashing: h1(k) = k mod 11, h2(k) = 7…
- Longest substring that can be turned into one repeated letter with at most k replacements (sliding window, window − maxfreq ≤ k). What is…