How to generate (enumerate) 2**N tuples representing all vertices of unit hypercube in N-dimensional hyperspace ?
Claudio Grondi
claudio.grondi at freenet.de
Wed Jan 4 12:51:17 EST 2006
Heiko Wundram wrote:
> Claudio Grondi wrote:
>
>>Heiko Wundram wrote:
>>
>>>def perm(n):
>>> return (tuple(((1,-1)[(t>>i)%2] for i in xrange(n)))
>>> for t in xrange(2L**n))
>>
>>Isn't this kind of coding beeing the result of suffering from the
>>post-pyContest illness syndrom?
>
>
> I don't think what Paul Rubin posted is the sign of pyContest illness, as I
> use two-level generator expressions such as this quite often in my code.
> Why I didn't give this as the reponse to the OP was because it seems that
> he's not that familiar with Python to be able to read this efficiently and
> grap the concept behind the implementation immediately, that's why I
> thought an explicit loop was in order.
>
> But for any sufficiently advanced Python coder, I don't think this is
> unreadable in the least.
>
> --- Heiko.
List comprehension is a nice thing when standalone.
I am usually able to read it from the left to the right and understand
directly.
But with nested list comprehensions I don't see directly what is going
on, because there are more than one identifier I don't know about at the
time of reading the expression and I am forced to read the entire
nestings with eventually some more code spread over it. The trouble is,
that there are no visual hints toward understanding of the used
algorithm like it is the case in the non-list-comprehension version and
I usually have to re-read the nested list comprehension from the right
to the the left in order to get the idea. I don't want to be forced to
read from the right to the left as I am used to read left-right,
top-down and I expect any text (also source code) to be that way.
Similar critics comes sometimes up when someone learns the German
language, because you are forced to read also a very, very long sentence
up to its end, before it is clear what is the action. I consider it as a
problem which would be nice to get rid of if possible, but it is much
easier to try to influence coding style than the usage of a language.
Can usage of deep (i.e. more than two levels) nested list comprehensions
be considered bad coding style?
Claudio
More information about the Python-list
mailing list