我試圖在 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我們得到 acarry = 1并且將與下一個總和相加。
IE
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]
請幫助我解決這個問題的最佳解決方案。
uj5u.com熱心網友回復:
好吧,所有其他答案都非常適合添加 2 個數字(數字串列)。
但如果你想create a program which can deal with any number of 'numbers',
這是你可以做的...
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.insert(0, 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.insert(0, carry) # If carry is non-zero, insert it
return final # 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]
希望這是有道理的!
uj5u.com熱心網友回復:
如果我理解正確,您希望它是這樣的: [6, 9, 8], [5, 9, 2] -> 698 592 = 1290 -> [1, 2, 9, 0]
在這種情況下,我的第一個想法是將數字轉換為字串,將它們組合為一個字串并將其轉換為 int,然后將兩個值相加并再次轉換為整數串列......你可以試試這個:
def get_sum_as_list(list1, list2):
first_int = int(''.join(map(str,list1)))
second_int = int(''.join(map(str,list2)))
result = [int(num) for num in str(first_int second_int)]
return result
uj5u.com熱心網友回復:
另外兩個答案顯示了在 int 串列和字串和 int 之間重復轉換的解決方案。我認為這有點作弊,完全隱藏了演算法。
在這里,我提出了一個解決方案,它直接操縱整數串列以構建第三個整數串列。
from itertools import chain, repeat # pad list with 0 so they are equal size
from operator import add # add(x,y) = x y
def padded(l1, l2):
"padded([1, 2, 3], [1, 2, 3, 4, 5]) --> [0, 0, 1, 2, 3], [1, 2, 3, 4, 5]"
padded1 = chain( repeat(0, max(0, len(l2)-len(l1))), l1 )
padded2 = chain( repeat(0, max(0, len(l1)-len(l2))), l2 )
return padded1, padded2
def add_without_carry_same_size(l1, l2):
"add_without_carry([6, 9, 8], [5, 9, 2]) --> [11, 18, 10]"
return map(add, l1, l2)
def flatten_carry(l):
"flatten_carry([11, 18, 10]) --> [1, 2, 9, 0]"
c = 0
for i in range(len(l)-1, -1, -1):
c, l[i] = divmod(c l[i], 10)
if c > 0:
l[:] = [c] l
def list_add(l1, l2):
'''
list_add([6, 9, 8], [5, 9, 2]) --> [1, 2, 9, 0]
list_add([9, 9, 9, 9, 9], [1]) --> [1, 0, 0, 0, 0, 0]
'''
p1, p2 = padded(l1, l2)
l3 = list(add_without_carry_same_size(p1, p2))
flatten_carry(l3)
return l3
相關檔案:
- 內置函式
map; itertools.chain;itertools.repeat;operator.add;- 內置函式
divmod。
uj5u.com熱心網友回復:
嘗試了以下邏輯
def list_sum(lst1, n, lst2, m, output):
i, j, k, carry = n - 1, m - 1, max(n, m), 0
while i >= 0 and j >= 0:
output[k] = (lst1[i] lst2[j] carry) % 10
carry = (lst1[i] lst2[j] carry) // 10
i = i - 1
j = j - 1
k = k - 1
while i >= 0:
output[k] = (lst1[i] carry) % 10
carry = (lst1[i] carry) // 10
i = i - 1
k = k - 1
while j >= 0:
output[k] = (lst2[j] carry) % 10
carry = (lst2[j] carry) // 10
j = j - 1
k = k - 1
output[0] = carry
print(output)
上面代碼中的輸出引數取自下面
outputSize = (1 max(n, m))
output = outputSize * [0]
并呼叫函式
list_sum(lst1, n, lst2, m, output)
uj5u.com熱心網友回復:
這是一種可能的解決方案:
(i)join每個串列創建一對整數的字串表示
(ii) 將它們轉換為整數,
(iii) 添加它們,
(iv) 將總和轉換為字串
(v) 將每個數字分隔為ints
def list_sum(lst1, lst2):
out = []
for i, lst in enumerate([lst1, lst2]):
if len(lst) > 0:
out.append(int(''.join(str(x) for x in lst)))
else:
if i == 0:
return lst2
else:
return lst1
return [int(x) for x in str(out[0] out[1])]
list_sum([6,9,8],[5,9,2])
輸出:
[1, 2, 9, 0]
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/407415.html
標籤:
