Python 3D Academyবাংলা

Permutations: seating guests

🌍 In real life. Three guests, Ana, Bob and Cy, are coming to dinner, and there are three chairs in a row. In how many ways can they sit? For the first chair you can pick any of the 3 guests. For the second, anyone who is still standing: 2 choices. The last chair gets whoever is left. Each different order is a different seating: Ana-Bob-Cy is not the same as Cy-Bob-Ana.

Now a harder version: Ana and Bob have had an argument and must not sit next to each other. You could list every seating and throw away the bad ones, but it is smarter never to build them: the moment Bob would sit down next to Ana, skip that choice.

The idea in one sentence: to list every permutation (every order) of the items, fill the positions one at a time with any item not used yet, explore the rest, then undo, so that every order is built exactly once.

Its words:

  • permutation: an arrangement of all the items in some order; order matters
  • used: which items are already placed, so none is placed twice
  • constraint: a rule an answer must obey (Ana and Bob not side by side)
  • pruning: skipping a choice as soon as it breaks a rule, so nothing built from it is ever explored

Step by step:

  1. if every seat is filled, the path is one seating: collect a copy
  2. otherwise, for each guest not used yet: seat them (mark used, add to path)
  3. explore the next seat
  4. undo: remove them from the path and mark them unused, then try the next guest

The tree has 3 branches, then 2, then 1: 6 seatings at the bottom.

Why it is correct. At each seat the loop tries every guest who is still standing, so every possible order is reached by some path; and since each path is a different sequence of choices, no order is reached twice. The used marks stop anyone from being seated twice, and the undo stands the guest up again so that later branches see the right people still standing.

Pruning a constraint. To keep Ana and Bob apart, check before seating someone: if the person in the last chair and this guest are Ana and Bob, skip the choice. The whole subtree below it, every seating that would start that way, is never built. That is the difference between pruning and filtering: filtering builds everything, then throws most of it away.

What it costs, by counting. n choices for the first seat, n − 1 for the next, and so on: n! = n × (n − 1) × … × 1 permutations, each copied in n steps, so listing them is O(n × n!):

  • 3 guests: 6
  • 5 guests: 120
  • 10 guests: 3,628,800

n! grows even faster than 2ⁿ, so only small n are practical. Python's itertools.permutations lists them in the same order.

def permutations(items):
    out, path = [], []
    used = [False] * len(items)
    def go():
        if len(path) == len(items):
            out.append(path[:])
            return
        for i in range(len(items)):
            if not used[i]:
                used[i] = True         # choose a guest not seated yet
                path.append(items[i])
                go()                   # explore the next seat
                path.pop()             # undo: stand them up again
                used[i] = False
    go()
    return out

def seatings_apart(guests, a, b):
    path = []
    used = [False] * len(guests)
    def go():
        if len(path) == len(guests):
            return 1
        count = 0
        for i, g in enumerate(guests):
            if used[i]:
                continue
            if path and {path[-1], g} == {a, b}:
                continue               # prune: a and b would sit together
            used[i] = True
            path.append(g)
            count += go()
            path.pop()
            used[i] = False
        return count
    return go()

from itertools import permutations as library_permutations

print(permutations(["ana", "bob", "cy"]))
print(len(list(library_permutations(range(5)))))
print(seatings_apart(["ana", "bob", "cy", "dev"], "ana", "bob"))

Mistakes and edge cases.

  • forgetting used[i] = False in the undo: the guest stays marked, so later branches think they are still seated, and most seatings are missed
  • choosing from the start index as in combinations: that makes combinations, not permutations; every order is a separate answer here, so every unused item is a choice
  • filtering instead of pruning: correct, but builds all n! seatings first; prune as soon as a rule breaks
  • repeated items: with ["a", "a", "b"] the same order comes out twice; skipping a value already tried at this seat fixes it
  • an empty list: there is exactly one way to arrange nothing: [[]]

Quiz

  1. What does this print?

    def permutations(items):
        out, path = [], []
        used = [False] * len(items)
        def go():
            if len(path) == len(items):
                out.append(path[:])
                return
            for i in range(len(items)):
                if not used[i]:
                    used[i] = True         # choose a guest not seated yet
                    path.append(items[i])
                    go()                   # explore the next seat
                    path.pop()             # undo: stand them up again
                    used[i] = False
        go()
        return out
    
    print(permutations([1, 2, 3])[:3])
  2. How many ways can 5 guests sit in 5 chairs in a row?

    • 120 = 5 × 4 × 3 × 2 × 1
    • 25
    • 32
  3. permutations([1, 2, 3]) returns only [[1, 2, 3]]. After which line is the undo missing?

    def permutations(items):
        out, path = [], []
        used = [False] * len(items)
        def go():
            if len(path) == len(items):
                out.append(path[:])
                return
            for i in range(len(items)):
                if not used[i]:
                    used[i] = True
                    path.append(items[i])
                    go()
                    path.pop()
        go()
        return out
  4. What is the difference between pruning and filtering?

    • Pruning skips a bad choice before exploring anything under it; filtering builds every answer and then throws the bad ones away
    • They give different answers
    • Filtering is always faster
  5. Listing every permutation of n items: what is the Big-O?

    • O(n × n!)
    • O(2ⁿ)
    • O(n²)

Coding tasks

  1. Write permutations(items): every order of the items, as a list of lists, built by filling one position at a time with each item not used yet, in the items' order (so permutations([1, 2]) is [[1, 2], [2, 1]]).

  2. Write seatings_apart(guests, a, b): how many ways the guests can sit in a row so that a and b are never next to each other. Prune: never seat someone next to the person in the last chair if together they are a and b.