K. John Michel
K. John Michel

Reputation: 45

How to range numbers based on two number in python

I wanted to generate numbers starting from 0 to 111111111111 in sequence and the number list i want only 1 and 0 like this in order not randomly:-

0
01
10
11
001
010
011
100
101
110
111
etc..

and this How to generate numbers based on a pattern in python does not have the right answer

Upvotes: -1

Views: 122

Answers (3)

python_user
python_user

Reputation: 7113

I am posting as an answer based on my understanding, might be wrong.

from itertools import product

def pattern(order):
    yield '0'
    for i in range(1, order):
        yield from (''.join(map(str, j)) for j in product(range(2), repeat=i+1) if sum(j))

for i in pattern(3):
    print(i)

Output

0
01
10
11
001
010
011
100
101
110
111

Upvotes: 0

Shivam Agrawal
Shivam Agrawal

Reputation: 491

So it looks like you want to get all 2-bit numbers then all 3-bit numbers and so on... (will it be 1 in the beginning, or the 0 is correct? I have assumed 0 is correct)

You can do it like:

last_no = 0b111111111111 # or (2 ** 12) - 1
i = 2

print(0)
while 2 ** i < last_no:
    for j in range(1, 2 ** i):
        print(f"{j:#0{i + 2}b}"[2:])
    i += 1
else:
    for j in range(1, last_no + 1):
        print(f"{j:#0{i + 2}b}"[2:])

output:

0
01
10
11
001
010
011
100
101
110
111
0001
0010
0011
...and so on

Upvotes: 0

kennyvh
kennyvh

Reputation: 2854

It looks like you want to print every digit in a 12-bit integer, so we can print the number as a binary literal with 12-bits padded with 0's:

for i in range(2 ** 12):
    print(f"{i:#012b}"[2:]) # strip "0b" prefix

Upvotes: 1

Related Questions