简体   繁体   中英

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'

For example, given [1,2,5,6] where k is 7, return True since 2+5 is 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):

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).

If you don't want to count cases like L = [1] , k = 2 , you can do this:

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 个长度的序列

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM