Gabriel Genellina wrote: > At Thursday 28/9/2006 22:07, Lawrence D'Oliveiro wrote: > > >How about this: (where n is the integer you want to convert): > > > > "".join([["0", "1"][(1 << i & n) != 0] for i in > > range(int(math.ceil(math.log(n, 2))) - 1, -1, -1)]) > > Uhm... so to generate a binary string you have to import the math > module, convert the integer to float, compute a non-standard > logarithm, and then... > What if n<=0? > Too much, don't you think? :)
Having recently discovered the joy of obfuscated python thanks to the Code Golf challenges, here's the shortest non-recursive function I came up with (all integers, signed): f=lambda n:'-'[:n<0]+''.join(str(m&1)for m in iter( lambda x=[abs(n)]:(x[0],x.__setitem__(0,x[0]>>1))[0],0))[::-1]or'0' Any takers ? ;-) George -- http://mail.python.org/mailman/listinfo/python-list