【发布时间】:2022-01-08 04:26:31
【问题描述】:
我正在尝试在 Python 中查找两个列表/数组的总和。
例如:
给你两个随机整数列表lst1和lst2,大小分别为n和m。这两个列表都包含来自0 to 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]
请帮助我解决这个问题。
【问题讨论】:
-
有什么问题?您的代码适用于给定的输入。
-
有时它会从索引错误中列出错误。我不知道为什么。还有其他更简洁且执行时间更短的解决方案吗?
-
在哪些输入上会引发此错误?
-
我看到一个列表的一个实例“被另一个索引索引”。 (一个典型的复制和粘贴错误。“仅携带”部分是不必要地复制的,而且无论如何都过于复杂。)一旦错误得到修复,请考虑Code Review@SE。
-
要找出你的代码有什么问题,你需要调试它。 This article 有一些很棒的技巧可以帮助您入门。
标签: python python-3.x list algorithm