Data Structures & AlgorithmsModerateTCS NQT · Infosys pattern
Convert the infix expression to postfix (^ is right-associative, higher than and /, which are higher than + and −). What is printed?
Convert the infix expression to postfix (^ is right-associative, higher than * and /, which are higher than + and −). What is printed?
def to_post(e):
prec = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3}
out, st = [], []
for ch in e:
if ch.isalnum(): out.append(ch)
elif ch == '(': st.append(ch)
elif ch == ')':
while st[-1] != '(': out.append(st.pop())
st.pop()
else:
while st and st[-1] != '(' and (prec[st[-1]] > prec[ch] or (prec[st[-1]] == prec[ch] and ch != '^')):
out.append(st.pop())
st.append(ch)
while st: out.append(st.pop())
return ''.join(out)
print(to_post("a+b*(c^d^e-f)/g"))- A. abcd^e^f-*g/+
- B. abcde^^f-g/*+
- C. abcde^^-f*g/+
- D. abcde^^f-*g/+
Correct answer: D. abcde^^f-*g/+
Inside the brackets, c^d^e groups as c^(d^e) → cde^^, then −f → cde^^f−. b*(…) then /g is left-associative: b(…)*g/. Finally a + … → a…+. Treating ^ as left-associative gives cd^e^.
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
- Evaluate the postfix expression with single-digit operands. What is printed? python st = [] for t in "62/3-42+": if t.isdigit()…
- 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…