[英]How to find pairs of integers in a list that add up to a target in O(N)?
[英]Find pairs of numbers in a list that add up to 10
給定一個數字列表,我想找到所有加起來為 10 的數字對。
如何在 Python 中編寫 function 來執行此操作?
只需將與10的差存儲在一組中:
def find(arr, total):
d = set()
for e in arr:
if e in d:
print total-e, e
break
d.add(total-e)
s = [1,5,3,10,11,7,2]
find(s, 10)
l = [1, 3, 4, 5, 6, 7, 8, 9]
[(x,y) for x in l for y in l if x+y==10]
這個問題很老了,但我想我會貢獻自己的答案,因為在撰寫本文時提供的兩種解決方案都有細微的錯誤:一個只提供一對加起來為 10 的數字; 另一個重復使用數字(例如,即使 5 只在列表中出現一次,除了重復對之外,(5, 5) 也被列為解決方案)。
使用 itertools 庫,您可以執行以下操作:
from itertools import combinations
def pair_sums(arr, expected=10):
return [x for x in combinations(arr, 2) if sum(x) == expected]
arr1 = [2, 4, 5, 6, 8]
pair_sums(arr1) # returns [(2, 8), (4, 6)]
arr2 = [2, 5, 7, 5, 9, 3]
pair_sums(arr2) # returns [(5, 5), (7, 3)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.