I cannot print a list(vector)

Asked

Viewed 65 times

-1

I’m trying to make a decimal to binary converter follow the code:

n = int(input('Insira um número decimal para conversão em binário '))
cont = []
aux = 0
while n > 1:
  if(n % 2 == 0):
    cont.insert(aux,n % 2)
    n = n // 2
  else:
    cont.insert(aux,n % 2)
    n = n // 2
  aux+=1

aux = len(cont)

while aux >= 0:
  print(cont[aux])
  aux-=1

I tried to replace the last while with:

for i in range(len(cont), -1, -1):
  print(cont[i])

however I could not and still gives the error Indexerror: list index out of range at the time of the cont print, how can I print the cont?

  • 1

    Welcome to Stackoverflow! The last index of a vector is always the size of the same - 1, because the indexes always start with 0.

  • 1

    That’s right, thank you, I was wrong too another part of the code, but I got vlw

  • https://answall.com/a/451231/112052

4 answers

1

Instead of inserting the digits at the bottom of the list and then reversing it, why not always insert the new elements at the beginning of the list? So they’re already in the right order.

Just always use the zero index on insert, thus:

n = # ler o número

result = []
while n > 0:
    result.insert(0, n % 2) # insere sempre no início da lista
    n //= 2

# depois você imprime os números como achar melhor

# um em cada linha
for i in result:
    print(i)

# ou todos juntos na mesma linha
print(''.join(map(str, result)))
print(*result, sep='')

Having the numbers in the correct order makes it easy to print. You can use the for as it was already doing, or if you want, print all on the same line, either using join or the options of print.

Note: you don’t need the if/else. In your code you did it:

if(n % 2 == 0):
    cont.insert(aux,n % 2)
    n = n // 2
else:
    cont.insert(aux,n % 2)
    n = n // 2

I mean, he did the exact same thing in if and in the else. If the same thing is done regardless of the condition, then eliminate the condition.


Another option (with caveats, see comments below) is to construct the value using calculations only. Ex:

n = 21
result = expoente = 0
while n > 0:
    n, digito = divmod(n, 2)
    result += (10 ** expoente) * digito
    expoente += 1

print(result) # 10101

I used divmod, which already returns the split result and the rest of it (is how to use // and % at once).

Remember that in this case I’m generating a number on base 10, the digits of which are the same as n base 2 (in the example above, the digits 10101 equals to 21 in base 2, but the value of it is "ten thousand one hundred", so no use result thinking he’s worth twenty-one).


Finally, this transformation is valid as an exercise, but if you only want to show the number in base 2, just do print(f'{n:b}'), as you have suggested another answer.

1


Try to change this line:

aux = len(cont)

For this:

aux = len(cont) - 1

0

Only change the size of aux or add - 1 will not work in the above case:

Follow a solution based on your reasoning:

n = int(input('Insira um número decimal para conversão em binário '))
cont = []

while n >= 1:
    cont.append(n % 2)   
    n = n // 2

for item in cont[::-1]:
    print(item)

0

Another interesting way to implement a converter decimal for binário is:

print('=' * 68)
print(f'\033[34m{"Conversor Decimal para Binário":^68}\033[m')
print('=' * 68)

cont = 0
while True:
    cont += 1
    if cont == 1:
        msg = f'um'
    else:
        msg = f'outro'

    n = int(input(f'Insira {msg} número em decimal para converte-lo em binário: '))
    print(f'\033[32mO binário de "{n}" é: {n:b}\033[m')

    resp = input('Desejas converter outro valor? [S/N] ').upper()
    while (len(resp) != 1) or (resp not in 'SN'):
        print('\033[31mValor INVÁLIDO! Digite apenas "S" ou "N"!\033[m')
        resp = input('Desejas converter outro valor? [S/N] ').upper()
    if resp == 'N':
        break

Note that when we execute the algorithm we are asked a decimal number (number in decimal base) and, after entering the value and pressing enter, the algorithm converts this value to binary and asks us if we want to perform another conversion. If we want to convert another value, just press the key s and at this time will be again requested new value.

Observing

The program will be terminated after the user presses the key N.

Browser other questions tagged

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