More about Alcides Fonseca
Go Back

Python list combinations of size N

Written by Alcides Fonseca at 1198505334

Yesterday I was implementing a OOP structure of Poker in Python for a friend, and I wanted it to be perfect. I even wrote some lambda expressions :) But when it comes of checking for pairs of triples, I wanted the code to be as more extensible as possible. It was late and I hadn’t practice my recursion for a while, so a lot of google searches came out with the following useful code:




def comb(x,n):
\"\"\"Generate combinations of n items from list x\"\"\"
if n==0:
yield []
return
for i in xrange(len(x)-n+1):
for r in comb(x[i+1:], n-1):
yield [x[i]] + r


A recursive generator! Wow…