How do I exchange the values of A and B

Roy Smith roy at panix.com
Tue Nov 21 07:28:59 EST 2000


In article <3A1A007B.B21C2DF7 at engcorp.com>, Peter Hansen 
<peter at engcorp.com> wrote:

> Charlie Kilmer wrote:
> > 
> > How do I exchange the values
> > int A = x;
> > int B= y;
> > 
> > here x and y are the values
> > 
> > how do exchange the values so that
> > int A = y;
> > int B = x;
> 
> Umm, in what language?  'Cause that ain't Python...

There's an old XOR hack that works in Python just as well as any other 
language:

>>> A = 47
>>> B = 103
>>> A = A ^ B
>>> B = A ^ B
>>> A = A ^ B
>>> A
103
>>> B
47

Other than curiosity value, it's hard to imagine why you would want to 
do such a thing in a HLL.  Back in the days of writing things in 
assembler, it was an occasionally useful hack to avoid blowing a 
register or burning a memory cycle, but if any of us were worried about 
that kind of stuff any more we wouldn't be writing in python.

Of course, this only works for integers.

No, wait, on a pdp-11 you could move a float into two adjacent GP 
registers, operate each half independently at integers, and then move 
the register pairs back into the FP registers, so it does work on 
floating point too!  But, if you had GP registers to blow on this, you 
could just use one GP pair as a temp and do the normal 3-way swap, so 
what would be the point? :-)



More information about the Python-list mailing list