[Tutor] Re: Bit strings

Charlie Clark charlie at begeistert.org
Wed Oct 22 04:41:45 EDT 2003


On 2003-10-22 at 09:21:50 [+0200], tutor-request at python.org wrote:
> >>> bitStrings(5)
> ['00000', '00001', '00010', '00011', '00100', '00101', '00110', '00111', 
> '01000', '01001', '01010', '01011', '01100', '01101', '01110', '01111', 
> '10000', '10001', '10010', '10011', '10100', '10101', '10110', '10111', 
> '11000', '11001', '11010', '11011', '11100', '11101', '11110', '11111']
> 
> Checking bitStrings(6) and bitStrings(7) gives the correct answer as 
> well. Perfect.  I'm sure the padding/stripping part could be written a 
> little more effective, but it fits my needs for right now.  Thanks.
> 
> The next task would be what if I needed strings that used 0, 1, and 2.  
> We'd need a decimal to trinary function.  Or if I needed strings that 
> used all digits from 0 to (n-1).  Hmm, I think I know how I will be 
> spending my weekend.

Reading this last paragraph makes me think that you are looking for a 
generic base converter. I'm sure there are lots of examples around there 
but it should be quite easy to come up with your own using a recursive 
function. I'm very bad at designing these myself but in theory you can 
convert any decimal to another base by dividing recursively and adding the 
modulus to the result. You can build this into a lazy function which can 
operate on a range for you and use "zfill" to generate your formatted 
strings.

Quick sketch 
9 / 2, 9 % 2 = 4, 1
4 / 2, 4 % 2 = 2, 0
2 / 2, 2 % 2 = 1, 0
1 / 2, 2 % 1 = 0, 0 # this tells us we're at the end of anaylsis

The trick is to turn this into something like 1 0 0 + 1 and to test it with 
other values. The nice thing about division and modulo is that we don't 
have to worry about what is the maximal value in any particular base.

Charlie



More information about the Tutor mailing list