Skip to content

Instantly share code, notes, and snippets.

@deostroll
Forked from anonymous/comb.py
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deostroll/4b556abbc20be7521884 to your computer and use it in GitHub Desktop.
Save deostroll/4b556abbc20be7521884 to your computer and use it in GitHub Desktop.
Combinations in python using a generator
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))
yield 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(list(a))
print 'Total: ', len(list(a))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment