Without getting into the merit that this is not a good way to add up numbers (I’m assuming it’s just for language learning purposes), one idea is to use reversed
to traverse from last to first digit, and zip
to scroll through both lists at the same time.
Then, just add the digits, and if the sum is greater than 9, accumulate the value for the next iteration:
lista1 = [9, 9, 9, 9]
lista2 = [0, 0, 0, 1]
acc = 0
result = []
for d1, d2 in zip(reversed(lista1), reversed(lista2)):
soma = d1 + d2 + acc
result.insert(0, soma % 10) # insere sempre no início da lista
acc = soma // 10
if acc > 0: # se ainda tem algum valor acumulado
result[0] += 10 * acc
print(result) # [10, 0, 0, 0]
I don’t understand why the result shouldn’t be [1, 0, 0, 0, 0]
(to maintain the rule of having one digit for each element of the list), but anyway (if it were to do this, just change result[0] += 10 * acc
for result.insert(0, acc)
).
It just wasn’t clear if the lists always have the same size. For example, if you typed "1", the list would be just [1]
or [0, 0, 0, 1]
? But how will you know the amount of zeroes to be added? Because you won’t know until you’ve read all the numbers.
Anyway, if you want to be more generic, I suggest using zip_longest
, iterates by lists of different sizes, and still has the option to add zero for the missing values:
from itertools import zip_longest
lista1 = [9, 9, 9, 9]
lista2 = [1]
acc = 0
result = []
for digitos in zip_longest(reversed(lista1), reversed(lista2), fillvalue=0):
acc, digito = divmod(sum(digitos) + acc, 10)
result.insert(0, digito)
if acc > 0:
result[0] += 10 * acc
print(result) # [10, 0, 0, 0]
I also used divmod
to already have the result of the division and the rest of this same division, all at once (just to show another way of doing), plus sum
to sum up the digits.
In this way, you could do it in a much more generic way, that add up several numbers at once:
numeros = []
while True: # ler vários números
n = input('digite o número (ou zero para encerrar): ')
# não estou validando se é número mesmo
if n == '0': break
# transforma cada dígito do número em um elemento da lista
numeros.append(list(map(int, n)))
# ao final do while, "numeros" é uma lista contendo várias listas (e cada uma representa um número)
from itertools import zip_longest
acc = 0
result = []
for digitos in zip_longest(*map(reversed, numeros), fillvalue=0):
acc, digito = divmod(sum(digitos) + acc, 10)
result.insert(0, digito)
if acc > 0:
result[0] += 10 * acc
Easier to operate as two integers.
– Augusto Vasques