Embercode
✕
Recursion and BacktrackingQuick quiz

Explicit stack

6 questions. Covers Explicit stack in Python.

Questions 1 to 5 of 6

  1. 1. In one pass of the while stack: loop in fill_stack, what is the order of the steps for a cell that passes both checks?

    Use the arrows to put the steps in order.

    1. 1.Check that the row and column are inside the grid
    2. 2.Check that the cell still has the old colour
    3. 3.Paint the cell with the new colour
    4. 4.Push its four neighbours onto the stack
    5. 5.Pop the top cell from the stack
  2. 2. What does this code print? ``python stack = [] stack.append(4) stack.append(9) print(stack.pop()) stack.append(2) print(len(stack)) while stack: print(stack.pop()) ``
  3. 3. Before the main loop starts, fill_stack does four things. Put them in the order the code does them.

    Use the arrows to put the steps in order.

    1. 1.Create a list to use as the stack, with the start cell as its first item
    2. 2.Run the loop while the stack is not empty
    3. 3.Return at once if the old colour equals the new colour
    4. 4.Read the old colour from the start cell
  4. 4. What does this code print? fill_stack is the function from the lesson, with the same bounds and colour checks. ``python DR = [-1, 1, 0, 0] DC = [0, 0, -1, 1] def fill_stack(grid, start_r, start_c, new_color): old_color = grid[start_r][start_c] if old_color == new_color: return stack = [(start_r, start_c)] while stack: r, c = stack.pop() if r < 0 or r >= len(grid) or c < 0 or c >= len(grid[0]): continue if grid[r][c] != old_color: continue grid[r][c] = new_color for d in range(4): stack.append((r + DR[d], c + DC[d])) grid = [[1, 2, 1], [1, 1, 0]] fill_stack(grid, 0, 0, 3) print(grid) ``
  5. 5. This loop is the body of fill_stack, placed after the colour guard has run. It is meant to paint every cell connected to the start. DR and DC are the same row and column steps as in the function above. What is the bug? ``python stack = [(start_r, start_c)] while stack: r, c = stack.pop() if grid[r][c] != old_color: continue if r < 0 or r >= len(grid) or c < 0 or c >= len(grid[0]): continue grid[r][c] = new_color for d in range(4): stack.append((r + DR[d], c + DC[d])) ``

3 question(s) left on this page.