Python 在一个列表中查找一对数字,其总和为10
给出一个数字列表,我想找出所有加起来等于10的数字对Python 在一个列表中查找一对数字,其总和为10,python,Python,给出一个数字列表,我想找出所有加起来等于10的数字对 如何在Python中编写函数来实现这一点?只需将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) 一个很好的
如何在Python中编写函数来实现这一点?只需将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)
一个很好的小例子大约需要三分钟。我印象深刻。:)您应该使用
set
而不是dict
来测试成员资格。很高兴这是O(n)
。存储补码并查看它们何时被找到是一种很好的方法。您有一个错误:您在s中为e编写了,但您的意思是在arr中为e编写
,很难说您需要什么。你能举一些输入和输出的例子吗?
l = [1, 3, 4, 5, 6, 7, 8, 9]
[(x,y) for x in l for y in l if x+y==10]