ProgrammingHardAmazon OA · Flipkart coding round
Which technique is the reliable fix for a recursive DFS on a path graph with n = 10^5 nodes in Python, which otherwise raises RecursionError?
- A. Use yield from so the recursion uses no call stack
- B. Rewrite the DFS with an explicit stack or deque, since the default recursion limit is about 1000 frames
- C. Wrap the call in try/except RecursionError and retry with the same recursion
- D. Add @lru_cache to the DFS function so it stops recursing
Correct answer: B. Rewrite the DFS with an explicit stack or deque, since the default recursion limit is about 1000 frames
An explicit stack keeps the traversal state in heap memory, so the depth does not hit the interpreter's frame limit. Caching or wrapping does not reduce the number of nested calls.
More Python Programming questions
- What is printed? python import math print(math.floor(-2.5), math.ceil(-2.5), math.trunc(-2.5), int(-2.5))
- What is printed? python x = 'xyz' print(f'{x!r:>7}|{len(x):03d}|{x[::-1]:^5}|')
- What is printed? python from itertools import chain print(list(chain.fromiterable(['ab', 'c'])), ''.join(chain([['x'], ['y', 'z']])))
- What is printed? python print(repr("it's"), repr('say "hi"'), len('x41101'), len(r'n'))
- What is printed? python print(pow(3, -1, 8)) try: print(pow(4, -1, 8)) except ValueError: print('not invertible')
- What is printed? python import math print(math.comb(100, 50) % 1000, 2100 % 9, sum(map(int, str(2100))) % 9)