ProgrammingVery hardTCS CodeVita · Infosys HackWithInfy
What is printed?
What is printed?
g = {1: [2, 3], 2: [4], 3: [], 4: []}
stack = [1]
out = []
while stack:
u = stack.pop()
out.append(u)
stack.extend(g[u])
print(out)- A. [1, 3, 2, 4]
- B. [1, 2, 4, 3]
- C. [1, 2, 3, 4]
- D. [1, 3, 4, 2]
Correct answer: A. [1, 3, 2, 4]
This is an iterative DFS. Pushing the children in list order means the last child is popped first, so 3 comes before 2. To mimic recursive preorder exactly, push children in reverse.
More Python Programming questions
- What is printed? python s = list(range(10)) print(s[8:2:-3], s[::-4], s[-3:])
- What is printed? python a = [1, 2, 3, 4, 5] a[1:3] = [9] 4 print(a)
- What is printed? python print(repr('abc'[5:]), repr('abc'[-10:2]), [1, 2][3:0:-1])
- What is printed? python s = 'banana' print(s.find('an', 2), s.rfind('an'), s.find('x'), s.index('na', 3))
- What is printed? python print('aaaa'.count('aa'), 'aaaa'.replace('aa', 'b'), len('aaaaa'.split('aa')))
- What is printed? python x = 3.14159 print(f"{x:08.3f}|{x:>8.2e}|{42:#x}|{'ab'!r:>6}")