1

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)?

Maciej Ziarko
  • 11,494
  • 13
  • 48
  • 69

2 Answers2

5

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
Scott Griffiths
  • 21,438
  • 8
  • 55
  • 85
4
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)
Hugh Bothwell
  • 55,315
  • 8
  • 84
  • 99