iq.lab
Python starts when a code cell comes near or you run one
11 Backtracking

Checkpoint

Backtracking

Eleven items from both lessons: choice trees, then pruning. Every input is new, so work each one on paper: draw the tree level by level, or write path down after every choose and every unchoose, because that is where the classic mistakes show. The last two items are code; the rest take a few minutes each.

  1. Question 1 of 11.

    This search lists the strings for a phone number, one letter per digit. Key 2 holds abc and key 7 holds pqrs.

    KEYS = {"2": "abc", "7": "pqrs"}
    
    def letters(digits):
        out = []
        path = []
        def explore(i):
            if i == len(digits):
                out.append("".join(path))
                return
            for ch in KEYS[digits[i]]:
                path.append(ch)
                explore(i + 1)
                path.pop()
        explore(0)
        return out

    How many times is explore called for letters("27"), the first call included? Type a whole number.

    calls

    Type a number: 12, -1, 0.5 and 3/4 all work.

  2. Question 2 of 11.

    This version saves path itself, with no copy, and it has no unchoose step. Type exactly what it prints.

    def subsets(items):
        result = []
        def explore(i, path):
            if i == len(items):
                result.append(path)
                return
            explore(i + 1, path + [items[i]])
            explore(i + 1, path)
        explore(0, [])
        return result
    
    print(subsets([5, 8]))
    
  3. Question 3 of 11.

    This orderings search has no used list. It skips a number when that number is already in path:

    def orderings(nums):
        result = []
        path = []
        def explore():
            if len(path) == len(nums):
                result.append(path[:])
                return
            for x in nums:
                if x in path:
                    continue
                path.append(x)
                explore()
                path.pop()
        explore()
        return result

    What does orderings([4, 4, 6]) return?

  4. Question 4 of 11.

    This combination sum passes 0 to the next call where the lesson passed i. Type exactly what it prints.

    def combos(candidates, target):
        candidates = sorted(candidates)
        result = []
        path = []
        def explore(start, remaining):
            if remaining == 0:
                result.append(path[:])
                return
            for i in range(start, len(candidates)):
                c = candidates[i]
                if c > remaining:
                    break
                path.append(c)
                explore(0, remaining - c)
                path.pop()
        explore(0, target)
        return result
    
    print(combos([2, 1], 3))
    
  5. Question 5 of 11.

    The test for ) in this bracket search reads closed < n instead of closed < opened:

    def brackets(n):
        out = []
        path = []
        def build(opened, closed):
            if len(path) == 2 * n:
                out.append("".join(path))
                return
            if opened < n:
                path.append("(")
                build(opened + 1, closed)
                path.pop()
            if closed < n:
                path.append(")")
                build(opened, closed + 1)
                path.pop()
        build(0, 0)
        return out

    How many strings does brackets(2) return? Type a whole number.

    strings

    Type a number: 12, -1, 0.5 and 3/4 all work.

  6. Question 6 of 11.

    This word search never marks a cell with "#", so it never needs to put a letter back:

    def word_exists(board, word):
        rows, cols = len(board), len(board[0])
        def match(r, c, i):
            if r < 0 or r >= rows or c < 0 or c >= cols:
                return False
            if board[r][c] != word[i]:
                return False
            if i == len(word) - 1:
                return True
            return (match(r + 1, c, i + 1) or match(r - 1, c, i + 1)
                    or match(r, c + 1, i + 1) or match(r, c - 1, i + 1))
        for r in range(rows):
            for c in range(cols):
                if match(r, c, 0):
                    return True
        return False

    What does word_exists([["A", "B"]], "ABA") return?

  7. Question 7 of 11.

    On a 6 by 6 board, queens stand at row 0, column 1; at row 1, column 3; and at row 2, column 5. How many squares of row 3 are safe from all three queens? Use the three sets: columns, row - col and row + col. Type a whole number.

    safe squares

    Type a number: 12, -1, 0.5 and 3/4 all work.

  8. Question 8 of 11.

    Each task asks for every answer, not a count. With the rule of thumb of about 107 simple steps per second, which one can a backtracking search finish in about a second?

  9. Question 9 of 11.

    This subsets search has no keep-or-drop. Each call prints path as soon as it starts, then loops from start the way combination sum did. Type exactly what it prints, one line per print.

    def subsets(items):
        path = []
        def explore(start):
            print(path)
            for i in range(start, len(items)):
                path.append(items[i])
                explore(i + 1)
                path.pop()
        explore(0)
    
    subsets([1, 2, 3])
    
  10. Question 10 of 11.

    Run the tests before you submit. This question counts as correct if your latest run passes every check.

    Code itEvery way to write the letters

    Write case_variants(s), which returns every string you can make from s by writing each letter in lowercase or in uppercase. Other characters, such as digits, stay as they are. "a1b" gives the 4 strings "a1b", "a1B", "A1b" and "A1B", in any order. s has at least one character. (This is LeetCode 784, Letter Case Permutation.)

    Each character is one level of the choice tree: a letter has two branches and any other character has one. ch.isalpha() is True when ch is a letter, and ch.lower() and ch.upper() give its two forms.

    ⌘+Enter runsPython starts when a code cell comes near or you run one
    Write your code where the starter says raise NotImplementedError, then press Run tests. Each check says what it expects.
  11. Question 11 of 11.

    Run the tests before you submit. This question counts as correct if your latest run passes every check.

    Code itChoose k numbers, and stop early

    Write choose(n, k), which returns every way to pick k different numbers from 1 to n. Each way is a list, and each way appears once: [1, 3] and [3, 1] are the same way. choose(4, 2) gives the 6 ways [1, 2], [1, 3], [1, 4], [2, 3], [2, 4] and [3, 4], in any order. You may assume 1 ≤ k ≤ n. (This is LeetCode 77, Combinations.)

    One test asks for choose(24, 22). It has only 276 ways, but a search with no prune test makes almost 17 million calls, nearly all on paths that can never reach 22 numbers. Before you choose a number, check that enough numbers are left to fill the path.

    ⌘+Enter runsPython starts when a code cell comes near or you run one
    Write your code where the starter says raise NotImplementedError, then press Run tests. Each check says what it expects.
0 of 11 answered. Unanswered questions count as wrong.