
Code
Backtracking
Backtracking explores every possible choice, one step at a time, and undoes a choice when it leads nowhere. It follows a simple recipe: choose, explore, un-choose.
def permutations(items):
results, path = [], []
def explore():
if len(path) == len(items): # a full answer
results.append(path.copy())
return
for item in items:
if item not in path:
path.append(item) # choose
explore() # explore
path.pop() # un-choose
explore()
return results
print(permutations([1, 2, 3])) # 6 orderings
Backtracking gets much faster when you prune: stop exploring a branch as soon as you know it can't work.
Assignment
The guild airship can carry exactly target kilos. Write
subset_sums(weights, target) that returns every combination of crates
whose weights add up to exactly target.
weightsis a list of positive whole numbers. Use each crate at most once.- Each combination is a list, with crates in the same order as in
weights. subset_sums([2, 3, 5, 7], 10)gives[[2, 3, 5], [3, 7]](any order).- Return
[]if nothing works.
The guild airship can carry exactly target kilos. Write
subset_sums(weights, target) that returns every combination of crates
whose weights add up to exactly target.
weightsis a list of positive whole numbers. Use each crate at most once.- Each combination is a list, with crates in the same order as in
weights. subset_sums([2, 3, 5, 7], 10)gives[[2, 3, 5], [3, 7]](any order).- Return
[]if nothing works.
main.py Python sleeping
Press Run to try your code, then Check to test it.