0

I needed to produce all the binary numbers from 000-111 in string form and my first approach is shown below. However, it struck me that this must be a very inefficient way to do this. Are there better ways please, and how are they more efficient?

 # print all binary numbers from 000 - 111
    for i in range(2):
        for j in range(2):
            for k in range(2):
                value = f'{i}{j}{k}'
                print(value)
Robin Andrews
  • 3,514
  • 11
  • 43
  • 111
  • I don't see how this is a duplicate of the linked question. I'm asking for a way to produce multiple binary values in an efficient way, while the other question just addresses a single conversion. – Robin Andrews Dec 29 '18 at 15:02

3 Answers3

3

You could do:

for i in range(8):
    s = bin(i)[2:]
    print(s.zfill(3))

Output

000
001
010
011
100
101
110
111
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
1

You can use this;

>>> ['{:03b}'.format(i) for i in range(8)]
['000', '001', '010', '011', '100', '101', '110', '111']

>>> ['{:03b}'.format(i) for i in range(2,8)]
['010', '011', '100', '101', '110', '111']

Just will have to convert the range to decimal.

Vicrobot
  • 3,795
  • 1
  • 17
  • 31
0

Here are a few different ways to do it, and their results. The performance difference is minor in the grand scheme of things, so you shouldn't worry too much.

%%timeit
for i in range(2):
    for j in range(2):
        for k in range(2):
            value = f'{i}{j}{k}'
            print(value)

Original Result: 823 µs ± 49.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%%timeit
for i in range(8):
    print("{0:03b}".format(i))

Result: 784 µs ± 35.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%%timeit  
for i in range(8):    
    print(bin(i)) #note that this does not produce the output exactly as you'd want it

Result: 807 µs ± 36.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%%timeit 
for i in range(8): 
    print(bin(i)[2:].rjust(3, '0')) #this one really surprised me, i didn't expect it to be fastest.

Result: 773 µs ± 43.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

And just an itertools version if you didn't want to use binary representations. Note that i have excluded library import for the sake of comparison.

from itertools import product
bits = ['0', '1']
%%timeit
for i in product(bits, repeat = 3):
    print(''.join(i))

Result: 801 µs ± 65.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Paritosh Singh
  • 6,034
  • 2
  • 14
  • 33