Binary numbers

Steve Holden sholden at holdenweb.com
Tue Feb 6 11:55:15 EST 2001


<sampe99 at my-deja.com> wrote in message news:95p7ks$9e6$1 at nnrp1.deja.com...
> Does anyone know an easy way to get a list of binary numbers within a
> certain range in python? E.g for
> n=1 [0],[1]
> n=2 [0,0],[0,1],[1,0],[1,1]
> n=3 [0,0,0],[0,0,1] a.s.o
> 
> I need this for n<=18...
> 
> Thanks a lot in advance
> 
> /Sam
> 
Maybe this will help:

def bin(n):
    l = []
    while n > 0:
        l[:0] = [n%2]
        n /= 2
        if l == [] : return [0]
    return l

>>> bin(3)
[1, 1]
>>> bin(5)
[1, 0, 1]
>>> bin(11)
[1, 0, 1, 1]

regards
 Steve





More information about the Python-list mailing list