Show all possibilities of Python numbers

Asked

Viewed 80 times

-1

How do I show all possibilities according to the number of bit quantization, for example: user: 8 levels bits: 3 need to show then:

0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1

my code so far, and it needs to be without using many ready-made functions, same root mode. please help me:

while True:
    nbits = 0
    niveis = int(input('Digite os niveis de quantização:'))
    q = niveis
    v = ""
    if niveis < 0:
        print("Números negativos não são permitidos")
    elif niveis == 0:
        nbits = 1
        print("O número de bits: ", nbits )
    elif niveis == 1:
        nbits = 2
        print("O número de bits: ", nbits )
    elif niveis%2 == 0:
        while (niveis>1):
            niveis = niveis/2
            nbits = (nbits + 1)
        print("O número de bits: ", nbits )
        print("Possibilidades")
    matriz = [[q],[nbits]]
    for l in range(1, q):
        for c in range(0, nbits):
            if l == 1:
                v += ("0")
    print(v)

1 answer

1


For N bits, the highest possible value is 2N - 1, then just loop to that value and print the binary value:

niveis = int(input('Digite os niveis de quantização:'))
for i in range(2 ** niveis):
    print(f'{i:0{niveis}b}')

Output (to niveis equal to 3, for example):

000
001
010
011
100
101
110
111

The format 0{niveis}b shows the binary number, using a number of spaces equal to niveis and complete with zeros on the left if necessary. View documentation to learn more.


But if you want to print with a space between the digits, just manipulate the string:

for i in range(2 ** niveis):
    print(' '.join(c for c in f'{i:0{niveis}b}'))

Another alternative is to use itertools.product, that already generates all the possibilities for you:

from itertools import product
niveis = int(input('Digite os niveis de quantização:'))
for i in product('01', repeat=niveis):
    print(' '.join(i))

product returns tuples containing zeros and ones, so just join them with join, that the elements will be separated by a space. The output of the 2 codes above - to niveis equal to 3 - is:

0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.