我正在尝试在Python中找到两个列表/数组的总和。
例如:
你有两个随机整数列表lst1
和lst2
,分别具有大小n
和m
。这两个列表都包含来自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
,并且它将与下一个 sum 相加。
也就是说
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]
我该尝试什么?