[Tutor] reverse diagonal
eryksun
eryksun at gmail.com
Sun Dec 2 03:19:57 CET 2012
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]
~i returns the value (-i - 1):
>>> [~i for i in range(4)]
[-1, -2, -3, -4]
If a sequence index is negative, Python normalizes it by adding the
sequence length. For example, seq[-1] == seq[3], where len(seq) == 4.
You can think of the sequence index on a ring:
2
3 1
-4 0
-3 -1
-2
The corresponding negative index of the sequence is 180 degrees (pi
radians) around the ring. So the bitwise complement of index i
traverses the sequence in reverse order.
More information about the Tutor
mailing list