Outputting/finding first n numbers of Natural Binary Code:
import math
def binary_print(n):
m = int(math.ceil(math.log(n, 2)))
for i in range(n):
b = str(bin(i)[2:])
print((m - len开发者_开发百科(b)) * '0' + b)
My question is:
Do you know any other way to do this in Python? Maybe faster? Or shorter (less code)?
Well this is shorter, not sure about faster:
def binary_print(n):
print '\n'.join('{:0{}b}'.format(x, (n-1).bit_length()) for x in range(n))
Example usage:
>>> binary_print(6)
000
001
010
011
100
101
def binary_values(n):
fmt = "{0:0"+str((n-1).bit_length())+"b}"
for i in range(n):
print fmt.format(i)
Note: (n-1).bit_length() fixes a fencepost error (otherwise if n is a power of two it prints 1 too many leading zeros).
Might also be able to speed it up a bit more by unrolling a lookup,
def binary_values(n):
fmt = ("{0:0"+str((n-1).bit_length())+"b}").format
for i in range(n):
print fmt(i)
精彩评论