Added an explanation for testing with
if __name__ == '__main__':
vegaseat
DaniWeb's Hypocrite
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
Gribouillis
Posting Maven
2,786 posts since Jul 2008
Reputation Points: 1,044
Solved Threads: 691
There are 1000 ways to do this, and you just added way #1001 :)
vegaseat
DaniWeb's Hypocrite
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
About the formatting in the previous example, you can also use the format operator
def binary(n, digits=8):
return "{0:0>{1}}".format(bin(n)[2:], digits)
See this snippet about the marvels of format().
Gribouillis
Posting Maven
2,786 posts since Jul 2008
Reputation Points: 1,044
Solved Threads: 691
Lambda always intrigues me:
# works with IronPython, Python2 and Python3
d = 255
# a recursive dec to bin function
d2b = lambda d: (not isinstance(d,int) or (d==0)) and '0' \
or (d2b(d//2)+str(d%2))
print(d2b(d)) # 011111111
Lardmeister
Posting Virtuoso
1,749 posts since Mar 2007
Reputation Points: 407
Solved Threads: 44
A rather straightforward one-liner to do the same thing:
>>> bin(10)[2:].rjust(8, '0')
'00001010'
It's true, only in 2005 we were with python 2.4 which had no bin() function. Also it's useful for beginners to see how one can implement bin() in pure python. It is a classical exercise in programming to display numbers in a different basis.
Gribouillis
Posting Maven
2,786 posts since Jul 2008
Reputation Points: 1,044
Solved Threads: 691