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"))
  1. A. abcd^e^f-*g/+
  2. B. abcde^^f-g/*+
  3. C. abcde^^-f*g/+
  4. 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^.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic