[Tutor] python string __add__

Scott Widney SWidney@ci.las-vegas.nv.us
Thu Jun 5 20:30:02 2003


> Then, you can either start dividing by two and collecting 
> remainders to convert that long directly to binary

Ah, I hear whispers of 'recursion' -- I cannot pass that up!  Please take a
look at this function definition:

#####
def decimalAsBinary(number):
    bits = []
    def get_bits(number):
        new_num, bit = divmod(number,2)
        bits.append(bit)
        if new_num > 0:
            get_bits(new_num)
    get_bits(number)
    result.reverse()
    print ''.join([str(bit) for bit in bits])
    return bits
#####

After reading Jeff's reply, I played with divmod() for a while and put this
together. It works: it prints a string representation of the binary
equivalent of the decimal number and returns a list of the ones and zeroes
therein.

However, it's ugly. I'd been looking for an excuse to try some of the new
features of the language (i.e. nested definitions). I think this could be
improved upon, but my brain is too addled to continue. Please pick it apart.


Scott