![](/img/trans.png)
[英]Given an array of N integers, and an integer K, find the number of pairs of elements in the array whose sum is equal to K
[英]Find a sum in n arrays equal to a given value?
假設我有 n 個數組:
a = [1,2,3,4,5,6]
b = [0,3,5,7,9,10]
c = [3,3,5,6,7,8]
...
如何在這些數組中找到等於給定值 X 的總和?
當我這樣做時,我到了那里:
for i in a:
for j in b:
for k in c:
if i + j + k == X:
...
但它是硬編碼的,如何用 n 個數組來做呢?
這將生成任意數量的數組的product
並打印總和等於某個值的值。
import itertools
a = [1,2,3,4,5,6]
b = [0,3,5,7,9,10]
c = [3,3,5,6,7,8]
arrays = [a, b, c]
X = 15
for x in itertools.product(*arrays):
if sum(x) == X:
print("+".join(str(v) for v in x))
您可以將遞歸與加入單個 2D 列表的列表一起使用:
a = [[1,2,3,4,5,6], [0,3,5,7,9,10],[3,3,5,6,7,8]]
def sumof(a, idx, value, lst):
if value < 0:
return
if idx == len(a):
if (value == 0):
print(lst)
return
for x in a[idx]:
sumof(a, idx + 1, value - x, lst + [x])
sumof(a, 0, 22, [])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.