Skip to content

Instantly share code, notes, and snippets.

@quantumelixir
Created January 15, 2011 10:46
Show Gist options
  • Save quantumelixir/780830 to your computer and use it in GitHub Desktop.
Save quantumelixir/780830 to your computer and use it in GitHub Desktop.
Permutations and Combinations in Python
def permute(l) :
if len(l) == 1 :
yield l
else :
for i in range(len(l)) :
for j in permute(l[:i] + l[i + 1:]) :
yield [l[i]] + j
def combinations(l, r) :
if r == 1 :
for i in l :
yield [i]
elif len(l) == r :
yield l
else :
for j in combinations(l[1:], r - 1 ) :
yield j + [l[0]]
for j in combinations(l[1:], r) :
yield j
# Non-yield version
def perm(s, pre = '') :
if len(s) :
for i in range(len(s)) :
perm(s[:i] + s[i + 1:], pre + s[i])
else :
print pre
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment