[Tutor] Permutations? (original) (raw)

Tim Peters tim.peters at gmail.com
Sun Jul 25 19:34:05 CEST 2004


[Hee-Seng Kye, playing with permutations]

... p.s. By the way, does anyone have any idea if it would drive my computer (667 MHz and 512MB RAM) nuts to perm(range(12))?

Yes, that can't work. There are n! permutations of a collection with n elements, and 12! = 479001600. You'll run out of memory long before materializing a list of nearly half a billion 12-element lists.

You can use generators, though, to produce the permutations one at a time. The memory burden is trivial then, although it will still take a long time to generate half a billion results.

For example,

def perm(k): if k: for i, ith in enumerate(k): for x in perm(k[:i] + k[i+1:]): x.insert(0, ith) yield x else: yield []

for p in perm([1, 2, 3]): ... print p

[1, 2, 3] [1, 3, 2] [2, 1, 3] [2, 3, 1] [3, 1, 2] [3, 2, 1]



More information about the Tutor mailing list