You can use bit operations to use a number as an array of flag bits. To make this work, we must encode your True as a cleared bit, but False as the set bit. Thus, the number becomes zero if all bits are cleared.
This works well because the number of flags is fixed. Starting with an array of set bits, you need to clear them until the number becomes zero.
This provides faster verification of conditions for minor bits of complexity and cost when cleaning bits. Testing if the number is zero is much cheaper than applying all to any list of booleans.
Comments on this issue suggested keeping the score and list. When one of the values ββbecomes true, the counter either reaches the final value of the list length or decreases from the list length to zero. This will work, but it is redundant since the same fact is encoded twice as a counter and once as a number of Trues.
This combines an account and a list. It does not contain redundancy.
Start with 5 preset bits:
>>> bin((1<<5)-1) '0b11111'
Then clean them. This clears the 4th bit:
>>> bin(((1<<5)-1) & ~(1 << 3)) '0b10111'
This will allow your loop to have a state like the following loop:
flags = (1<<5)-1 n = 0 while flags: flags &= ~(1<<n) print bin(flags) n += 1
This cycle starts with 5 preset bits and clears them one at a time.
>>> flags = (1<<5)-1 >>> n = 0 >>> while flags: ... flags &= ~(1<<n) ... print bin(flags) ... n += 1 ... 0b11110 0b11100 0b11000 0b10000 0b0
Dan D.
source share