Add the integer value of one list to another. EX: [9,9,9]+[0,0,0,1]=[10,0,0,0]

Asked

Viewed 57 times

-3

All right, everybody?!

I’m having trouble implementing something like (in python):

I have lists, for example:

Lista1 = [9,9,9,9]
Lista2 = [0,0,0,1]

I want a date with something like: [10,0,0,0](list sum)

Type 9 + 1 (from last position), turn 10(obvious) the 1 goes up to the previous position of the list1, summing with the next 9, and the 0 takes the last position of the list sum, simple addition.

If anyone can help I’d appreciate it :)

Note: the entry (of any size) is date by the user. Then I read a string (of numbers), 'split' it number by number and turned them into integers.

  • Easier to operate as two integers.

1 answer

1


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
  • Friend, thank you. I apologize for the formulation of the question, it may have been confusing indeed. As for the merit of the functionality of the question, it is a teacher thing, I definitely know that this is not by far the simplest or best method to solve the problem. Anyway, I will improve the formulation of my questions in the community, I am new here. Helped me a lot.

Browser other questions tagged

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