[Tutor] Combination
Kent Johnson
kent37 at tds.net
Fri Jan 21 11:51:01 CET 2005
This question comes up regularly on comp.lang.python. Search the archives for 'combinations' to find
*many* discussions of how to do it. Also there are several recipes in the cookbook.
http://groups-beta.google.com/group/comp.lang.python?hl=en&lr=&ie=UTF-8&c2coff=1
http://aspn.activestate.com/ASPN/Cookbook/Python
Kent
Guillermo Fernandez Castellanos wrote:
> 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
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
More information about the Tutor
mailing list