Data Structures & AlgorithmsModerateTCS NQT · stack basics
Problem: What is the value of the reverse Polish expression '2 1 + 3 '? Run the stack code.
Problem: What is the value of the reverse Polish expression '2 1 + 3 *'? Run the stack code.
tokens = '2 1 + 3 *'.split()
st = []
for t in tokens:
if t in '+-*/':
b, a = st.pop(), st.pop()
st.append(a + b if t == '+' else a - b if t == '-' else a * b if t == '*' else a // b)
else:
st.append(int(t))
print(st[0])What is printed?- A. 7
- B. 5
- C. 9
- D. 11
Correct answer: C. 9
A stack evaluates postfix left to right: 2 1 + leaves 3, then 3 3 * leaves 9. Reading the tokens as infix with precedence (2 + 1 × 3) gives the tempting 5, and popping operands in the wrong order only matters for - and /.
More Coding Interview Problems questions
- Problem: What is the maximum matching size in the bipartite graph with left vertices {0,1,2}, right vertices {0,1,2} and edges (0,0)…
- Problem: How many integers x in [1, 100] satisfy x^2 ≡ 1 (mod 8)? Run the code. python print(sum(1 for x in range(1, 101) if (x x) % 8 ==…
- Problem: What is the smallest positive integer x with x ≡ 1 (mod 4) and x ≡ 2 (mod 5)? Run the code. python print(next(x for x in range(1…
- Problem: How many integers in [1, 100] have non-decreasing decimal digits (for example 1245 or 3399, but 2 digits only here)? Run the…
- Problem: What is the spiral (clockwise from the top-left) traversal of the matrix [[1,2,3],[4,5,6],[7,8,9]]? Print the list produced by…
- Problem: How many swaps does insertion sort perform on [3, 2, 1]? Count the shifts in the code. python a = [3, 2, 1] swaps = 0 for i in…