[Tutor] reverse diagonal
Dave Angel
d at davea.name
Sun Dec 2 03:35:27 CET 2012
On 12/01/2012 09:19 PM, 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))]
Folks, notice the symbol in front of the 'i' is a tilda, not a minus-sign.
> [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.
>
>
Thanks eryksun, I knew all those facts, but didn't connect them together
for this purpose. One's complement arithmetic works great with the
indexing rules to reverse an order. Good job.
Next level of subtlety:
[M[i][~i] for i,dummy in enumerate(M) ]
--
DaveA
More information about the Tutor
mailing list