Skip to content

Instantly share code, notes, and snippets.

Created February 25, 2015 13:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save anonymous/d8dc0e7e449cdc94f991 to your computer and use it in GitHub Desktop.
Save anonymous/d8dc0e7e449cdc94f991 to your computer and use it in GitHub Desktop.
Python code for combinations
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