Data Structures & AlgorithmsModerateCognizant · Capgemini pattern
Evaluate the postfix expression with single-digit operands. What is printed?
Evaluate the postfix expression with single-digit operands. What is printed?
st = []
for t in "62/3-42*+":
if t.isdigit(): st.append(int(t))
else:
b, a = st.pop(), st.pop()
st.append({'+': a + b, '-': a - b, '*': a * b, '/': a // b}[t])
print(st)- A. [8]
- B. [2]
- C. [-8]
- D. [6]
Correct answer: A. [8]
6/2 = 3, 3 − 3 = 0, 4·2 = 8, 0 + 8 = 8. The second popped value is the left operand; popping the other way round gives 2/6 = 0 and different results.
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
- What is printed? (deque operations) python from collections import deque d = deque([1, 2, 3]) d.appendleft(0); d.append(4) d.rotate(2)…
- What is printed? (singly linked list, delete every node whose value equals x) python class N: def init(s, v, n=None): s.v, s.n = v, n h =…
- What is printed? (finding the intersection node of two linked lists by switching heads) python class N: def init(s, v, n=None): s.v, s.n =…
- What is printed? (Java String vs StringBuilder) java String s = "ab"; s.concat("cd"); StringBuilder sb = new StringBuilder("ab")…
- What is printed? (counting sort on small values) python a = [4, 1, 3, 4, 2, 1, 0, 4] cnt = [0] 5 for x in a: cnt[x] += 1 for i in range(1…
- How many swaps does this bubble sort make, and how many passes run? python a = [5, 1, 4, 2, 8] swaps = passes = 0 for i in range(len(a)…