[Tutor] Re: Recursive Combinations?
Mon, 20 Aug 2001 10:14:42 -0500
Remco Gerlich wrote:
| On 0, Andrew Wilkins <email@example.com> wrote:
| > Thanks Remco!
| > I tried it out - doesn't do _quite_ what I wanted, but with that
| > (beautiful) code I can change it to do what I want! It just needs to
| > remove reverse orders (eg. (1,2) and (2,1), and remove like elements
| in pairs (eg. (1,1)).
| Oh, right. I'm immediately back to my old style of posting - almost,
| but not quite :)
| Both are easily remedied by generating only combinations that are in
| strictly ascending (or descending) order.
| That means using range(1, combination), but unfortunately that
| needs an extra check for length == 1.
| def combinations(length, n):
| if length == 0:
| return [()]
| if length == 1:
| return [(i,) for i in range(1,n+1)]
| return [ (i,)+combination for combination in combinations(length-1,n)
| for i in range(1, combination) ]
| Remco Gerlich
Hats off to you, Remco. :-) Now that I see the answer it seems simple,
but I really had a hard time coming up with a recursive combination
generator on my own.