[Tutor] python string __add__

Neil Schemenauer nas-pytut@python.ca
Thu Jun 5 22:35:02 2003


Scott Widney wrote:
> 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.

Here's (arguably) a cleaned up version:

    def d2b(n):
        if n == 0:
            return '0'
        bits = []
        while n:
            n, bit = divmod(n, 2)
            bits.append(str(bit))
        bits.reverse()
        return ''.join(bits)

Cheers,

  Neil