Created
February 25, 2015 13:31
-
-
Save anonymous/d8dc0e7e449cdc94f991 to your computer and use it in GitHub Desktop.
Python code for combinations
This file contains hidden or 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
from math import factorial as fact | |
def comb(seq, r): | |
n = len(seq) | |
total = fact(n) / (fact(r) * fact(n-r)) | |
pos = range(r) | |
c= [] | |
i = 0 | |
while i < total: | |
c.append(map(lambda x: seq[x], pos)) | |
k = r - 1 | |
if pos[k] + 1 < n: | |
pos[k] = pos[k] + 1 | |
else: | |
l = k - 1 | |
while l >= 0: | |
if pos[l] + 1 < n - r + (l + 1): | |
pos[l] = pos[l] + 1 | |
m = l + 1 | |
while m <= k: | |
pos[m] = pos[m-1] + 1 | |
m = m + 1 | |
break | |
l = l - 1 | |
i = i + 1 | |
return c | |
if __name__ == '__main__': | |
import pprint as pp | |
a = comb('abcdef', 2) | |
pp.pprint(a) | |
print 'Total: ', len(a) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment