我有一份清单lst = [2, 4, 5, 6, 7, 8]
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)
您已经得到了几个其他答案,但只是为了好玩,使用递归:
在每个递归步骤中,给定一个列表,我们选择head元素(命名为
x
)和列表的其余部分sublst
。如果在sublst
中有一个元素与x
求和以得到给定的数字,则返回x
和其他内容。这是递归发生的地方;我们只考虑了(x, y)
中y
在sublst
中的(x, y)
对,而不是sublst
中的^对。所以我们需要再次调用find_sum
,使用这个sublst
。当给定列表的长度为1或为空时,该递归过程结束;在这些情况下,没有配对要考虑,所以只返回一个空列表。注意这里的
else
是多余的,因为它前面有return
。但我还是喜欢它在那里以下是使用生成器的另一个版本:
试试这个:
输出:
当您调用
return
时,您正在结束函数。这意味着一旦你找到第一对,你的函数就结束了,你再也找不到了要解决这个问题,您应该在名为
good_pairs
(或任何您想要的)的函数中添加一个数组。与其写return (lst[i], lst[indices[target]])
,不如写good_pairs.append((lst[i], lst[indices[target]]))
最后,只需返回
good_pairs
列表然后用你想要的格式打印出来
最终代码:
我首先对数组进行排序,然后仅枚举数组的一半以防止重复。归功于@enzo
希望这有帮助,祝你好运:)
相关问题 更多 >
编程相关推荐