簡體   English   中英

求兩個 Arrays 之和

[英]Find the sum of Two Arrays

我試圖在 Python 中找到兩個列表/數組的總和。

例如:

您將獲得兩個隨機的 integer 列表,分別為大小nmlst1lst2 兩個列表都包含從0 to 9的數字(即,每個索引都存在單個數字 integer)。

這里的想法是將每個列表表示為數字 N 和 M 本身的 integer。

您需要找到兩個輸入列表的總和,將它們視為兩個整數並將結果放入另一個列表中,即 output 列表也將在每個索引處僅包含單個數字。

以下是我嘗試過的代碼:

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]

output:

[1, 2, 9, 0]

在這里,每個元素被求和,然后如果sum >=10 ,那么我們得到一個carry = 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]

請幫助我解決這個問題的最佳解決方案。

好吧,所有其他答案都非常適合添加 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]

希望這是有道理的!

如果我理解正確,您希望它是這樣的: [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

另外兩個答案顯示了在 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

相關文件:

嘗試了以下邏輯

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)

其中上面代碼中的 output 參數取自下面

outputSize = (1 + max(n, m))
output = outputSize * [0]

並稱為 function

list_sum(lst1, n, lst2, m, output)

你沒有提到你的名單會有多長。 所以考慮到它們不會那么長(無論如何,python 可以處理 bignums),為什么不做一個簡單的求和運算呢? 最后,這就是代碼應該模擬的內容。

import numpy as np
lst1 = [6, 9, 8] 
lst2 = [5, 9, 2]
lst1_len = len(lst1)
lst2_len = len(lst2)
if lst1_len >= lst2_len:
    lst2 = [0] * (lst1_len - lst2_len) + lst2
else:
    lst1 = [0] * (lst2_len - lst1_len) + lst1

common_len = len(lst1)

lst1_val = sum(np.array(lst1) * np.array([10**(-x) for x in range(-common_len + 1, 1)]))
lst2_val = sum(np.array(lst2) * np.array([10**(-x) for x in range(-common_len + 1, 1)]))
total = lst1_val + lst2_val
total_as_list = [int(x) for x in str(total)]

在哪里

print(total_as_list)
[1, 2, 9, 0]

這是一種可能的解決方案:

(i) join每個列表以創建一對整數的字符串表示

(ii) 將它們轉換為整數,

(iii) 添加它們,

(iv) 將總和轉換為字符串

(v) 將每個數字分隔為int s

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])

Output:

[1, 2, 9, 0]

代碼:

def addNums(*args):
    nums=[]
    for i in args:                                
        if i:
            i = list(map(str,i))               # Converts each element int to string['6', '9', '8'] , ['5', '9', '2']
            add=int(''.join(i))                # Joins string and convert to int  698 ,592
            nums.append(add)                   # Appends them to list [698, 592]

    Sum = str(sum(nums))                       # Sums the values and convert to string '1290'
    result=list(map(int,Sum))                  # Converts to list with each converted to int[1,2,9,0]
    
    return result
print(addNums([6, 9, 8], [5, 9, 2]))  
print(addNums([7, 6], [5, 9], [3, 5],[7, 4]))
print(addNums([]))

Output:

[1, 2, 9, 0]
[2, 4, 4]
[0]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM