Data Structures & AlgorithmsModerateWipro · Accenture pattern
What is printed? (Tower of Hanoi: number of moves and the 5th move)
What is printed? (Tower of Hanoi: number of moves and the 5th move)
moves = []
def hanoi(n, a, b, c):
if n == 0: return
hanoi(n - 1, a, c, b); moves.append(a + c); hanoi(n - 1, b, a, c)
hanoi(3, 'A', 'B', 'C')
print(len(moves), moves[4])- A. 7 AC
- B. 7 BA
- C. 8 BA
- D. 7 BC
Correct answer: B. 7 BA
T(n) = 2T(n − 1) + 1 = 2ⁿ − 1 = 7 moves. The sequence for 3 discs from A to C is AC, AB, CB, AC, BA, BC, AC – the 5th move is B → A. The middle (4th) move is always the largest disc A → C.
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- What is printed? (recursion output order) python out = [] def f(n): if n == 0: return out.append(n) f(n - 1) out.append(n) f(3) print(out)
- Solve the recurrences numerically: how many 'work units' does each do for n = 64? python from functools import lrucache @lrucache(None)…
- 0/1 knapsack, capacity 50: items (weight, value) = (10, 60), (20, 100), (30, 120). What do greedy-by-ratio and DP give? python items =…
- Activity selection: activities (start, finish). How many can one person attend, and which? python acts = [(1, 4), (3, 5), (0, 6), (5, 7)…
- Huffman coding: frequencies a:5, b:9, c:12, d:13, e:16, f:45. What is the total number of bits to encode the text? python import heapq f =…
- Longest common subsequence: what is the length and one LCS read back from the table (preferring the upper cell on ties)? python a, b =…