A puzzle for Pythonistas

Magnus Lie Hetland mlh at furu.idi.ntnu.no
Thu Feb 6 17:21:11 EST 2003


In article <b1tf7o$1i2$1 at news.hccnet.nl>, Anton Vredegoor wrote:
>On Thu, 6 Feb 2003 03:07:44 +0000 (UTC), mlh at furu.idi.ntnu.no (Magnus
>Lie Hetland) wrote:
>
>>Although you have already received several answers, I can't resist
>>writing up a solution to this one... The code below creates all
>
>Sometimes the obvious solution is overlooked ... I am glad you posted
>it!
[snip]
>There are a few problems with this code,

I'm sure -- it was written in a couple of minutes :)

> although I grant it must have
>been written by someone who saw the answer.
>
>a) the test should be 1<<j & i

Yes, of course. Sorry about that. (Or 2<<(j-1) ;)

>b) using compress this way causes a traceback?

Oh? It worked for me... What was the exception?

>After some refactoring:
[snip]

Right -- the refactoring here is, of course, a matter of taste, rather
than of correctness (although I agree that the subset function may be
useful in other contexts).

Note, btw, as I wrote in another post, that the call to bool(...) is
redundant.

>Now if someone could re-arrange the integers in a range so that the #
>of bits that are set increases monotonically this would be even better
>:-)

Hehe. You _could_ also just assemble all the combinations in a list
and sort it -- the sorting algorithm is very fast (even though it is
n*log(n)).

>Regards,
>	Anton

-- 
Magnus Lie Hetland               "Nothing shocks me. I'm a scientist." 
http://hetland.org                                   -- Indiana Jones




More information about the Python-list mailing list