Got it.

import copy

def rec(list,length):
        result=[]
        if len(list)<=length:
                return [list]
        for elem in list:
                temp=copy.deepcopy(list)
                temp.remove(elem)
                temp=rec(temp,length)
                for i in temp:
                        if i not in result:
                                result.append(i)
        return result

>>> rec([1,2,3,4,5],3)
[[3, 4, 5], [2, 4, 5], [2, 3, 5], [2, 3, 4], [1, 4, 5], [1, 3, 5], [1,
3, 4], [1, 2, 5], [1, 2, 4], [1, 2, 3]]

The logic is:
1) If I take a list L of length l > n, the n-length subgroups will be
the union of all the n-length subgroups of all the possible lists of
length l-1 derived from L.
2) We keep unique copies of the results (don't wanna have several
times [1,3,5] for instance). Will be easier when I'll install Python
2,4 and have the sets.
3) We stop the recursion when we have a list of th length we desire

Well... of course, thanks to Kent I've finded a bunch of much better
implementations. I still did mine for personal pleasure :-)

Thanks to all,

Guille

On Fri, 21 Jan 2005 12:44:54 -0800 (PST), Danny Yoo
<[EMAIL PROTECTED]> wrote:
> 
> 
> On Fri, 21 Jan 2005, Danny Yoo wrote:
> 
> > > 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)
> >
> >
> > There is a clean recursive way to define this.
> 
> Hi Guillermo,
> 
> Gaaa; I screwed up slightly.  *grin*
> 
> I just wanted to clarify: the function that I'm sketching out is not
> exactly the function that you're thinking of.  I'm doing more of a "give
> me all the subsets of L" kind of thing.
> 
> But if you can understand how to get all the subsets, you should be able
> to figure out how to get all the combinations of 'k' elements, because
> they're really similar problems.
> 
>
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to