Embercode
✕
Dynamic ProgrammingQuick quiz

DP bug hunt

8 questions. Covers Debugging lab: DP bugs in Python.

Questions 1 to 5 of 8

  1. 1. Coin change with coins [1, 2, 5] and amount 5 should print 4, but this code prints 0. Which line is the bug? ``python coins = [1, 2, 5] amount = 5 ways = [0] * (amount + 1) ways[0] = 0 for coin in coins: for a in range(coin, amount + 1): ways[a] += ways[a - coin] print(ways[amount]) ``
  2. 2. The minimum path sum for the grid [[1, 3, 1], [1, 5, 1], [4, 2, 1]] should be 7, but this code prints 2. Which is the bug? ``python grid = [[1, 3, 1], [1, 5, 1], [4, 2, 1]] rows = len(grid) cols = len(grid[0]) dp = [[0] * cols for _ in range(rows)] dp[0][0] = grid[0][0] for i in range(1, rows): for j in range(1, cols): dp[i][j] = grid[i][j] + min(dp[i - 1][j], dp[i][j - 1]) print(dp[rows - 1][cols - 1]) ``
  3. 3. One item with weight 2 and value 3, and capacity 5, should give 3, but this code prints 6. Which is the bug? ``python weights = [2] values = [3] capacity = 5 best = [0] * (capacity + 1) for item in range(len(weights)): w = weights[item] v = values[item] for c in range(w, capacity + 1): best[c] = max(best[c], best[c - w] + v) print(best[capacity]) ``
  4. 4. With coins [1, 2, 5] and amount 5, this code raises IndexError: list index out of range. Which is the bug? ``python coins = [1, 2, 5] amount = 5 ways = [0] * amount ways[0] = 1 for coin in coins: for a in range(coin, amount + 1): ways[a] += ways[a - coin] ``
  5. 5. What does this program print? ``python nums = [-3, -1, -2] current = 0 best = 0 for x in nums: current = max(x, current + x) best = max(best, current) print('largest sum of a run:', best) ``

5 question(s) left on this page.