[Tutor] Combination
Guillermo Fernandez Castellanos
guillermo.fernandez.castellanos at gmail.com
Fri Jan 21 10:16:19 CET 2005
Hi,
I'm trying to take a list and find all the unique combinations of that list.
I mean:
if I enter (1,2,3,4,5) and I watn combinations of 3, I want to find:
(1,2,3) but then not (2,1,3), (3,1,2),...
(1,2,4)
(1,2,5)
(2,3,5)
(3,4,5)
The thing is, I want to do it as a generic function, where I pass a
list, and the length of the combination I want,
For the pervious example, it would be:
createComb([1,2,3,4,5],3)
I have no idea how to do it in a generic way.
For a given list and a length of 4 I did this:
def createComb(positions):
"""Returns all possible combinations of position of nbUnit units"""
uniq={}
result=[]
for p1 in positions:
for p2 in positions:
for p3 in positions:
for p4 in positions:
uniq[p1]=0
uniq[p2]=0
uniq[p3]=0
uniq[p4]=0
if len(uniq)==4:
result.append([p1,p2,p3,p4])
uniq={}
return result
but is not very elegant...
Any suggestion?
Thanks,
G
More information about the Tutor
mailing list