Sub topic 7
Trying Every Ordering with Permutations
This chapter assumes you can write recursive functions in Python, have used itertools, and can read Big-O notation. It builds on the earlier chapters on search spaces and cost estimation.
Some problems ask for the best order of a set of items, not the best pair or the best subset. Examples include the order to visit cities, the order to schedule jobs, or the arrangement of letters in a word. In these problems the search space is the set of all permutations. A brute-force solution generates each ordering, scores it, and keeps the best one.
The Shape of the Search Space
A permutation of n distinct items is one arrangement of all of them. You have n choices for the first position, n − 1 for the second, and so on. That gives n! orderings in total. You can draw the enumeration as a tree. Each level fixes one more position, and each leaf is one complete ordering.
Brute-Force Traveling Salesman
The traveling-salesman problem asks for the shortest route that visits every city once and returns to the start. A tour is a cycle, so the starting city doesn't matter. Fixing city 0 as the start removes rotations that describe the same tour, which leaves (n − 1)! orderings to try.
import itertools
import math
def shortest_tour(dist):
n = len(dist)
best = math.inf
for perm in itertools.permutations(range(1, n)):
route = (0,) + perm + (0,)
cost = sum(dist[a][b] for a, b in zip(route, route[1:]))
best = min(best, cost)
return best
dist = [
[0, 10, 15, 20],
[10, 0, 35, 25],
[15, 35, 0, 30],
[20, 25, 30, 0],
]
print(shortest_tour(dist)) # 80, via 0 -> 1 -> 3 -> 2 -> 0Scoring each route costs O(n), so the total is O(n · (n − 1)!), which equals O(n!).
Generating Permutations Yourself
itertools.permutations is the right tool in Python. In an interview, though, you may be asked to write the generator yourself. Writing it also lets you add pruning later. The usual approach is recursive. Pick an unused item, append it, recurse, then undo the choice.
def permutations(items):
result = []
used = [False] * len(items)
current = []
def build():
if len(current) == len(items):
result.append(tuple(current))
return
for i, x in enumerate(items):
if not used[i]:
used[i] = True
current.append(x)
build()
current.pop()
used[i] = False
build()
return result
print(permutations(["A", "B", "C"]))How Fast n! Grows
Factorial growth is steeper than 2^n. Compare the counts against a budget of roughly 10^7 simple operations per second in Python:
| n | n! | Feasible in Python? |
|---|---|---|
| 8 | 40,320 | Instantly |
| 10 | 3,628,800 | A few seconds |
| 11 | 39,916,800 | Slow |
| 12 | 479,001,600 | No |
| 15 | about 1.3 × 10^12 | No, in any language |
In practice, permutation brute force works for n up to about 10 in Python and about 11 or 12 in a compiled language. If the input limit says n ≤ 8, the problem setter is probably expecting this approach.
Common Errors
- Forgetting the return leg. For a closed tour, the route must end back at the start. Leaving off the final
(0,)solves a different problem, the shortest path through all cities. - Permuting the fixed city. If you permute
range(n)and also prepend 0, city 0 appears twice in the route. - Duplicate items.
itertools.permutationstreats positions as distinct, so[1, 1, 2]yields 6 tuples, not 3. Wrap the result inset(...)or skip duplicates during recursion when you need distinct orderings. - Mutating shared state without undoing it. In a hand-written generator, every
appendandused[i] = Trueneeds a matching undo after the recursive call. Otherwise later branches see stale choices.
Exercise
You fix city 0 as the start in a 7-city symmetric traveling-salesman instance. How many orderings does shortest_tour try, and how many distinct tours are there once you account for reversal?
Show answer
It tries (7 − 1)! = 720 orderings. Each tour appears once in each direction, so there are 720 / 2 = 360 distinct tours.
Exercise
A job-scheduling problem asks for the best order of up to 13 jobs, and scoring an order takes O(n) time. Is a permutation brute force in Python reasonable? Justify it with numbers.
Show answer
No. 13! is about 6.2 × 10^9 orderings. With about 13 steps to score each one, the total is roughly 8 × 10^10 operations, which would take hours at about 10^7 operations per second. You need pruning or a smarter method, such as dynamic programming over subsets.