ProgrammingHardAmazon OA · Flipkart coding round
What is printed?
What is printed?
from collections import deque
def ladder(begin, end, words):
S = set(words)
q = deque([(begin, 1)])
seen = {begin}
while q:
w, d = q.popleft()
if w == end:
return d
for i in range(len(w)):
for ch in 'abcdefghijklmnopqrstuvwxyz':
nw = w[:i] + ch + w[i+1:]
if nw in S and nw not in seen:
seen.add(nw)
q.append((nw, d + 1))
return 0
print(ladder('hit', 'cog', ['hot', 'dot', 'dog', 'lot', 'log', 'cog']))- A. 5
- B. 4
- C. 3
- D. 0
Correct answer: A. 5
BFS over one-letter changes finds the path hit, hot, dot, dog, cog. The counter starts at 1 for the first word, so the path length is 5.
More Python Programming questions
- What is printed? python def can(a): s = sum(a) if s % 2: return False t = s // 2 dp = [False] (t + 1) dp[0] = True for x in a: for v in…
- What is printed? python def paths(g): R, C = len(g), len(g[0]) dp = [[0] C for in range(R)] dp[0][0] = 0 if g[0][0] else 1 for r in…
- What is printed? python def cool(p): hold, sold, rest = float('-inf'), 0, 0 for x in p: hold, sold, rest = max(hold, rest - x), hold + x…
- What is printed? python import bisect def inv(a): s, c = [], 0 for x in a: c += len(s) - bisect.bisectright(s, x) bisect.insort(s, x)…
- What is printed? python import bisect a = [10, 20, 20, 30] print([bisect.bisectleft(a, x) for x in (20, 25, 5, 40)])
- What is printed? python from functools import lrucache @lrucache(maxsize=None) def grid(r, c): if r == 0 or c == 0: return 1 return grid(r…