[英]How can i optimize my code by reducing the looping and conditioning
Here's my problem:这是我的问题:
Given a list of numbers and the number 'k', return whether any two numbers from the list add up to 'k'给定一个数字列表和数字“k”,返回列表中的任意两个数字是否加起来为“k”
For example, given [1,2,5,6]
where k
is 7, return True
since 2+5 is 7.例如,给定[1,2,5,6]
其中k
是 7,返回True
因为 2+5 是 7。
Here's my code;这是我的代码; I'd like some help on how to vectorize it.我想要一些关于如何矢量化它的帮助。
L = [3,4,1]
k = 5
for i in L:
for j in L:
if i+j == k:
print("True")
break
if i+j == k:
break
Vectorization doesn't seem like it would help here.矢量化似乎在这里没有帮助。
However, I propose a new algorithm that reduces complexity to O(N) from O(N^2):但是,我提出了一种新算法,将复杂度从 O(N^2) 降低到 O(N):
L = [3,4,1]
Lset = set(L)
k = 5
for x in L:
if k - x in Lset:
print("True")
break
I think the algorithm is fairly self-explanatory!我认为该算法是不言自明的! :) It basically iterates through L
and, for each number, checks if its "complimentary" (the number required to satisfy x + complimentary == k
) is present in the list (converted to a set for lower membership check cost). :) 它基本上遍历L
并且,对于每个数字,检查它的“免费”(满足x + complimentary == k
所需的数字)是否存在于列表中(转换为一组以降低成员资格检查成本)。
If you don't want to count cases like L = [1]
, k = 2
, you can do this:如果您不想计算L = [1]
, k = 2
,您可以这样做:
for x in L:
if k - x in Lset:
if k - x == x and L.count(x) < 2:
continue
print("True")
break
使用 itertools.combinations(L, 2) 为您提供所有 2 个长度的序列
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.