Start free

Beyond A level · 6 exercises

Python backtracking

Build an answer one choice at a time; when a choice leads nowhere, undo it and try the next. Recursion keeps track of where you are.

Check as early as you can whether a partial answer can still work, so dead ends are left quickly.

def subsets(items, chosen=[]):
    if not items:
        print(chosen)
        return
    subsets(items[1:], chosen + [items[0]])
    subsets(items[1:], chosen)

subsets([1, 2])

Watch for: Changing a shared list without undoing the change afterwards leaves the next choice with the wrong start.

Exercises

  1. N queensIn how many ways can n queens be placed on an n by n board so that no two attackExpert
  2. Sudoku solverSolve a sudoku: fill the empty cells (0) so every row, column and 3x3 box containsExpert
  3. Combination sumPrint every combination of the given numbers (each number may be used severalExpert
  4. All bracket patternsPrint every balanced arrangement of n pairs of round brackets, in dictionary orderExpert
  5. Choose k of nPrint every way to choose k different numbers from 1 to n, each in ascending order,Expert
  6. Word searchCan the word be traced in the grid by moving between neighbouring letters (up, down,Expert
Start with “N queens”