iterating bit-by-bit across int?

John Ladasky ladasky at my-deja.com
Thu Oct 23 18:45:37 EDT 2003
Matthew Wilson <mwilson at sarcastic-horse.com> wrote in message news:<slrnbpgah9.22u.mwilson at frank.homelinux.net>...
> I'm playing around with genetic algorithms and I want to write a
> function that mutates an integer by iterating across the bits, and about
> 1 in 10 times, it should switch a zero to a one, or a one to a zero.
> 
> I'm not sure how many bits are inside a python integer.  The library
> reference says at least 32.

It can vary from system to system, and is designed to accomodate
growth.  Use sys.maxint to find out how large an integer is on your
system.
 
> I'm thinking about writing a function that eats integers and poops out
> lists of bools; and then I can iterate through that, and change values
> in there.  But before I do that, does anyone have a better idea?

Using your approach, you would first need to disassemble the integer,
then reassemble it.  You can cut this bitwise cranking in half. 
Define an integer, in which 10% of the bits is a "1".  Then do an
exclusive-or operation between this integer and the one you wish to
mutate.

http://www.python.org/cgi-bin/moinmoin/BitwiseOperators

--
John J. Ladasky Jr., Ph.D.
Department of Biology
Johns Hopkins University
Baltimore MD 21218
USA
Earth




More information about the Python-list mailing list