interesting exercise
Steven D'Aprano
steven at REMOVE.THIS.cybersource.com.au
Tue May 8 00:31:04 EDT 2007
On Mon, 07 May 2007 20:45:52 -0700, Michael Tobis wrote:
> I have a reasonably elegant solution but it's a bit verbose (a couple
> dozen lines which I'll post later if there is interest). Is there some
> clever Pythonism I didn't spot?
Peering into my crystal ball, I see that your algorithm does the wrong
thing, and contains bugs too. You certainly don't need to partion the
sequence into three sub-sequences, or do that trick with the metaclass,
and it is more efficient to use list.extend() than sum.
Hang on... stupid crystal ball... that's somebody else's code. Maybe you
should just post your code here, so we can look at it?
In the meantime, here's a simple generator to do permutations with
repetition:
def permute_with_repetitions(seq):
if len(seq) <= 1:
yield list(seq)
else:
for i, item in enumerate(seq):
for tail in permute_with_repetitions(seq[:i] + seq[i+1:]):
yield [item] + tail
It doesn't do a test for the sequence containing duplicates, and I leave
it as an exercise to do selections of fewer items.
--
Steven.
More information about the Python-list
mailing list