ProgrammingHardGATE CS & IT · Infosys
What is printed?
What is printed?
def dfs(g, s):
seen, out, st = set(), [], [s]
while st:
u = st.pop()
if u in seen:
continue
seen.add(u)
out.append(u)
for v in reversed(g[u]):
st.append(v)
return out
g = {1: [2, 3], 2: [4], 3: [4], 4: []}
print(dfs(g, 1))- A. [1, 3, 4, 2]
- B. [1, 2, 4, 3]
- C. [1, 2, 3, 4]
- D. [1, 3, 2, 4]
Correct answer: B. [1, 2, 4, 3]
Pushing neighbours in reverse order makes the stack pop 2 first. Node 4 is reached through 2 before 3 is visited, so the order is 1, 2, 4, 3.
More Python Programming questions
- What is printed? python def hanoi(n, a, b, c, out): if n == 0: return hanoi(n - 1, a, c, b, out) out.append((a, c)) hanoi(n - 1, b, a, c…
- What is printed? python from collections import deque def islands(g): R, C = len(g), len(g[0]) seen = set() cnt = 0 for r in range(R): for…
- What is printed? python import heapq def refuel(target, start, stations): h = [] i = 0 fuel = start stops = 0 while fuel < target: while i…
- What is printed? python import heapq def jobs(items): items = sorted(items, key=lambda x: x[0]) h = [] for d, p in items…
- What is printed? python try: print(sorted([3, None, 1])) except TypeError: print('TypeError') print(max(['b', 'a'], key=str.upper)…
- What is printed? python s = 'hello' try: s[0] = 'j' except TypeError: print('immutable') t = s.replace('h', 'j') print(t, s)