例如,假设给定的整数列表:
int_list = list(range(-10,10))
[-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
如果 int_list
中的任何给定两个值的总和等于给定的 int,比方说 2
,最有效的方法是什么?
我在今天早上的一次技术电话采访中被问及如何使用包含 1 亿个项目的 int_list
有效地处理这种情况(我漫无目的地回答:/)。
我的第一个想法是:
from itertools import combinations
int_list = list(range(-10,10))
combo_list = list(combinations(int_list, 2))
desired_int = 4
filtered_tuples = list(filter(lambda x: sum(x) == desired_int, combo_list))
filtered_tuples
[(-5, 9), (-4, 8), (-3, 7), (-2, 6), (-1, 5), (0, 4), (1, 3)]
它甚至不适用于只有 range(-10000, 10000)
还有,有谁知道有什么好的在线Python性能测试工具吗?
最佳答案
对于任何整数A
,最多有一个整数B
,它们加起来等于整数N
。遍历列表、进行算术运算并进行成员测试以查看 B
是否在集合中似乎更容易。
int_list = set(range(-500000, 500000))
TARGET_NUM = 2
def filter_tuples(int_list, target):
for int_ in int_list:
other_num = target - int_
if other_num in int_list:
yield (int_, other_num)
filtered_tuples = filter_tuples(int_list, TARGET_NUM)
请注意,这将重复结果。例如。 (-2, 4)
是来自 (4, -2)
的单独响应。您可以通过更改函数来解决此问题:
def filter_tuples(int_list, target):
for int_ in int_list:
other_num = target - int_
if other_num in int_list:
set.remove(int_)
set.remove(other_num)
yield (int_, other_num)
关于python - 返回列表中任意两项的元组,如果相加等于给定的 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23964488/