[Tutor] What is the augmented assignment operator "^="
Andre Engels
andreengels at gmail.com
Mon Feb 19 12:46:08 CET 2007
2007/2/19, Dick Moores <rdm at rcblue.com>:
>
> At 02:17 AM 2/19/2007, Andre Engels wrote:
>
> >To understand these operators, you will have to think of the numbers
> >as binary numbers. Look at the digits. For two numbers x and y, x^y
> >is the effect of doing an exclusive or on all digits (that is, 0^1 =
> >1^0 = 1 and 0^0 = 1^1 = 0), & of doing an and (1&1 = 1,
> >1&0=0&1=0&0=0) and | is an or on all digits (1|1=1|0=0|1 = 1, 0|0 = 0).
> >
> >So 5^8 = 110 ^ 1000 = 0110 ^ 1000 = 1110 = 13
> >and 13^8 = 1110 ^ 1000 = 0110 = 5
>
> Thanks, Andre! I've got it for the three operators, for non-negative
> integers. But I'm not sure I understand how negative integers work.
> For example, is 3 & -3 = 1
> because it is 11 & -11 = 01, and that's because one of the first
> digits of 11 and -11 is not 1, and both of their 2nd digits ARE 1, Q.E.D.?
This has to do with the internal representation of negative numbers: -1 is
represented as 111....111, with one 1 more than maxint. -2 is 111...110 and
-3 is 111...101. Thus 3 & -3 is 11 & 111...101 = 1
Also, of what practical use are these things?
>
I guess they have their uses for people accustomed to dealing with hardware.
Apart from that, you can get a very space-efficient representation for
multiple boolean variables. If you have what looks like an array of
booleans, you could also represent it as a single natural number, for
example [true, true, false, false, true, false] would then be 1*1 + 1*2 +
0*4 + 0*8 + 1*16 + 0*32 = 19. Using such a representation and the above
operators would enable one to write
z = x & y
instead of
z = [x[i] and y[i] for i in range(len(x))]
when modelling the same using lists.
Of course this does come at the price of complicating
x[i] = true
to
x |= 2 ** i
which though not really longer does definitely look harder to understand.
--
Andre Engels, andreengels at gmail.com
ICQ: 6260644 -- Skype: a_engels
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070219/dd5741b5/attachment.html
More information about the Tutor
mailing list