Binary numbers

Steve Purcell stephen_purcell at yahoo.com
Tue Feb 6 18:14:27 CET 2001


Steve Purcell wrote:
> sampe99 at my-deja.com wrote:
> > 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...

Or even:

def binary(num):
    digits = map(lambda p, n=num: 2**p & n and 1, range(31))
    digits.reverse()                                        
    try: return digits[digits.index(1):]
    except: return [0]                  

for n in range(18):
    print n, '=', binary(n)


-- 
Steve Purcell, Pythangelist
Get testing at http://pyunit.sourceforge.net/
Available for consulting and training.
"Even snakes are afraid of snakes." -- Steven Wright




More information about the Python-list mailing list