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.
- Question 1 of 11.
This search lists the strings for a phone number, one letter per digit. Key 2 holds
abcand key 7 holdspqrs.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 outHow many times is
explorecalled forletters("27"), the first call included? Type a whole number.callsType a number: 12, -1, 0.5 and 3/4 all work.
- Question 2 of 11.
This version saves
pathitself, 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])) - Question 3 of 11.
This orderings search has no
usedlist. It skips a number when that number is already inpath: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 resultWhat does
orderings([4, 4, 6])return? - Question 4 of 11.
This combination sum passes
0to the next call where the lesson passedi. 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)) - Question 5 of 11.
The test for
)in this bracket search readsclosed < ninstead ofclosed < 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 outHow many strings does
brackets(2)return? Type a whole number.stringsType a number: 12, -1, 0.5 and 3/4 all work.
- 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 FalseWhat does
word_exists([["A", "B"]], "ABA")return? - 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 - colandrow + col. Type a whole number.safe squaresType a number: 12, -1, 0.5 and 3/4 all work.
- 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?
- Question 9 of 11.
This subsets search has no keep-or-drop. Each call prints
pathas soon as it starts, then loops fromstartthe 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]) - 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 fromsby 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.shas 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()isTruewhenchis a letter, andch.lower()andch.upper()give its two forms.Write your code where the starter saysraise NotImplementedError, then press Run tests. Each check says what it expects. - 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.Write your code where the starter saysraise NotImplementedError, then press Run tests. Each check says what it expects.