如何从列表中获取元素对的总和
我有清单 lst = [2, 4, 5, 6, 7, 8]
- 如果我搜索 12,我的输出应该是 (4,8), (5,7)
- 我当前的输出仅显示 (4,8)
- 如果我打印我的回报,那么列表的反向也打印像 (4,8), (5,7), (8,4), (7,5)
def find_sum(s, lst):
indices = {x: i for i, x in enumerate(lst)}
# print(indices)
for i, x in enumerate(lst):
target = s - x
if target in indices:
return (lst[i], lst[indices[target]])
return None
lst = [2, 4, 5, 6, 7, 8]
print(find_sum(12, lst))
预期的 (4,8), (5,7)
回答
尝试这个:
import itertools
def find_sum(s, lst):
return [x for x in itertools.combinations(lst, r=2) if x[0] + x[1] == s]
lst = [2, 4, 5, 6, 7, 8]
print(find_sum(12, lst))
输出:
[(4, 8), (5, 7)]
- @wjandrea Yes, you're right, I misread it as permutations. Either way, the OP's solution is O(n).