[Tutor] reverse diagonal

Steven D'Aprano steve at pearwood.info
Sun Dec 2 08:32:52 CET 2012


On Sat, Dec 01, 2012 at 09:19:57PM -0500, eryksun wrote:
> On Sat, Dec 1, 2012 at 11:31 AM, Dave Angel <d at davea.name> wrote:
> >
> > revdiag = [M[i][len(M)-1-i] for i  in range(len(M)) ]
> 
> You might sometimes see this using the bitwise invert operator ~ (i.e.
> __invert__, operator.invert):
> 
>     >>> M = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
> 
>     >>> [M[i][~i] for i in xrange(len(M))]
>     [3, 5, 7]

Ew!

There's something... smelly... about code using a bitwise-invert for 
indexing. Using it for bitwise operations is one thing. Using it to save 
writing two characters is just nasty.

http://www.joelonsoftware.com/articles/Wrong.html
http://c2.com/cgi/wiki?CodeSmell

It smacks of low-level optimization tricks which make no sense in a 
high-level language like Python. You aren't writing optimized assembler, 
if you want -i-1 write -i-1 !

> ~i returns the value (-i - 1):

Assuming certain implementation details about how integers are stored, 
namely that they are two-compliment rather than one-compliment or 
something more exotic.

Okay, just about every computer made since 1960 uses two-compliment 
integers, but still, the effect of ~i depends on the way integers are 
represented internally rather than some property of integers as an 
abstract number. That makes it a code smell.

And there is the risk that ~i will be misread as -i, which would be bad.



-- 
Steven


More information about the Tutor mailing list