python - 求两个数组的和

标签 python python-3.x list algorithm

我正在尝试在 Python 中查找两个列表/数组的总和。

例如:

你得到两个随机整数列表,分别是 lst1lst2,大小分别为 nm。这两个列表都包含从 0 到 9 的数字(即,每个索引都存在一位整数)。

这里的想法是将每个列表表示为数字 N 和 M 本身的整数。

您需要找到两个输入列表的总和,将它们视为两个整数并将结果放入另一个列表中,即输出列表也将在每个索引处仅包含单个数字。

以下是我尝试过的代码:

def list_sum(lst1, n, lst2, m) :
    i, j, sum, carry = 0, 0, 0, 0
    new_lst = []
    if n == 0 and m == 0:
        new_lst.append(0)
    elif n > 0 and m>0:
        while n > 0 and m > 0:
            sum = lst1[n - 1] + lst2[m - 1] + carry
            if sum >= 10:
                carry = 1
            else:
                carry = 0
            new_lst.append(sum % 10)
            n -= 1
            m -= 1
        while n > 0:
            if (lst1[n-1] + carry) >= 10:
                new_lst.append((lst1[n-1] + carry) % 10)
                carry = 1
            else:
                new_lst.append(lst1[n-1])
                carry = 0
            n -= 1
        while m > 0:
            if (lst2[m-1] + carry) >= 10:
                new_lst.append((lst2[m-1] + carry) % 10)
                carry = 1
            else:
                new_lst.append(lst1[m-1])
                carry = 0
            m -= 1
        if carry == 1:
            new_lst.append(1)
        new_lst.reverse()
    elif n == 0 and m > 0:
        new_lst.append(0)
        new_lst = new_lst + lst2
    elif n > 0 and m == 0:
        new_lst.append(0)
        new_lst = new_lst + lst1
    print(new_lst)

但是我觉得我在这里遗漏了一些东西,这并没有给我正确的组合答案。有时它错误列出了索引错误。我不知道为什么。

示例输入:

n = 3
lst1 = [6, 9, 8] 
m = 3
lst2 = [5, 9, 2]

输出:

[1, 2, 9, 0]

在这里,每个元素被求和,然后如果 sum >=10 则我们得到一个 carry = 1 并将与下一个总和相加。

1. 8+2= 10 >=10 hence carry=1 in first sum
2. 9+9+1( carry) = 19 >=10 hence carry=1
3. 6+5+1( carry) = 12>=10 hence carry=1
4. upend the carry to next position as 1
Hence resultant list would be [1, 2, 9, 0]

接下来我可以尝试什么?

最佳答案

嗯,所有其他答案都非常适合添加 2 个数字(数字列表)。
但是如果你想创建一个可以处理任意数量的“数字”的程序

Here's what you can do...

def addNums(lst1, lst2, *args):
    numsIters = [iter(num[::-1]) for num in [lst1, lst2] + list(args)]  # make the iterators for each list
    carry, final = 0, []                                                # Initially carry is 0, 'final' will store the result
    
    while True:
        nums = [next(num, None) for num in numsIters]                   # for every num in numIters, get the next element if exists, else None
        if all(nxt is None for nxt in nums): break                      # If all numIters returned None, it means all numbers have exhausted, hence break from the loop
        nums = [(0 if num is None else num) for num in nums]            # Convert all 'None' to '0'
        digit = sum(nums) + carry                                       # Sum up all digits and carry
        final.append(digit % 10)                                        # Insert the 'ones' digit of result into final list
        carry = digit // 10                                             # get the 'tens' digit and update it to carry

    if carry: final.append(carry)                                       # If carry is non-zero, insert it
    return final[::-1]                                                  # return the fully generated final list

print(addNums([6, 9, 8], [5, 9, 2]))                                    # [1, 2, 9, 0]
print(addNums([7, 6, 9, 8, 8], [5, 9, 2], [3, 5, 1, 7, 4]))             # [1, 1, 2, 7, 5, 4]

希望这是有道理的!

关于python - 求两个数组的和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70629597/

相关文章:

python - 打字:定义一个只能是某些字符串的类型?

python - 如何在不导入的情况下键入提示

python-3.x - 用ffmpeg切音频文件得到无持续时间python 3

python - 如何创建一个大小随着迭代而增加的数组

python - 如何将字符串 append 到 float 列表

python - 用于匹配导出为任务纸格式的 Omnifocus 项目的正则表达式

python - 如何在 openCV python 2.7 中添加 "Tracker"

Python遍历字典列表并保存到数据库

python-3.x - 如何减少数组中的重复数据

c# - 如何从偏移量开始并遍历整个列表?