iterating bit-by-bit across int?

Peter Hansen peter at engcorp.com
Fri Oct 24 09:18:18 EDT 2003


Anton Vredegoor wrote:
> 
> ladasky at my-deja.com (John Ladasky) wrote:
> 
> >> 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.
> 
> This creates a new problem which is interesting in itself. How to
> create this integer? 

I would think the simplest approach is (similar to a suggestion
already made about the original problem) to predefine a set of bitmasks,
each with only one bit set, then simply select one or more at random
and add (or OR) them together, then XOR the result with the original.

You could either iterate over the list of bitmasks, checking a 
random result at each step to decide whether to include that bitmask,
or you could just random.shuffle() the list, then select a random
number of entries from the start of the list.  Using the new sum()
(or a filter() with operator.add) would make the whole thing as
simple as a couple of function calls:

 genome = 12345678
 numMutations = random.randint(0, 4)
 mutant = genome ^ sum(random.shuffle(bitmasks)[:numMutations])

# done!!

The algorithm used to select the number of mutations to make could
of course be more sophisticated than the above...

-Peter




More information about the Python-list mailing list