Created
January 15, 2011 10:46
-
-
Save quantumelixir/780830 to your computer and use it in GitHub Desktop.
Permutations and Combinations in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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