ProgrammingHardTCS CodeVita · Infosys HackWithInfy
What is printed?
What is printed?
def rpn(tokens):
st = []
for t in tokens:
if t in ('+', '-', '*', '/'):
b = st.pop()
a = st.pop()
if t == '+':
st.append(a + b)
elif t == '-':
st.append(a - b)
elif t == '*':
st.append(a * b)
else:
st.append(int(a / b))
else:
st.append(int(t))
return st[0]
print(rpn(['-7', '2', '/']), rpn(['7', '-2', '/']), -7 // 2)- A. -3 -3 -4
- B. -4 -4 -4
- C. -3 -3 -3
- D. -3 -4 -4
Correct answer: A. -3 -3 -4
int(a / b) truncates toward zero, which is what the RPN evaluation needs, so -7 / 2 gives -3. Python's // floors toward minus infinity, so -7 // 2 is -4, which is the trap.
More Python Programming questions
- What is printed? python def ceildiv(a, b): return -(-a // b) print(ceildiv(7, 2), ceildiv(-7, 2), ceildiv(6, 3), ceildiv(1, 5))
- What is printed? python def atmost(a, k): l = s = c = 0 for r, x in enumerate(a): s += x while s > k: s -= a[l] l += 1 c += r - l + 1…
- What is printed? python from itertools import accumulate a = [3, 1, 4, 1, 5, 9, 2] print(list(accumulate(a, max)), list(accumulate(a…
- What is printed? python def comps(n, edges): p = list(range(n)) def find(x): while p[x] != x: p[x] = p[p[x]] x = p[x] return x cnt = n for…
- What is printed? python def spiral(m): out = [] while m: out += m.pop(0) m = [list(r) for r in zip(m)][::-1] return out print(spiral([[1…
- What is printed? python def climb(n, steps): dp = [0] (n + 1) dp[0] = 1 for i in range(1, n + 1): for s in steps: if i - s >= 0: dp[i] +=…