How to check if N can be expressed as the sum of two other numbers in a specific list

I have a list:

l = [1,3,4,6,7,8,9,11,13,...]

and the number n.

How to effectively check whether a number can nbe expressed as the sum of two numbers (duplicates are allowed) in the list l.

If the number is in the list, it is not taken into account if it cannot be expressed as two numbers (for example, for l = [2,3,4] 3 will not be counted, but 4 will be.

This, embarrassingly, is what I tried:

def is_sum_of_2num_inlist(n, num_list): 

num_list = filter(lambda x: x < n, num_list)

for num1 in num_list:
    for num2 in num_list:
        if num1+num2 == n:
            return True

return False

thank

+4
source share
4 answers

If I have a problem with OP, then -

repeats are allowed within the list l, , , , . , , , , .

itertools.combinations. , . sum .

from itertools import combinations

l = [1,3,4,6,7,8,9,11,13]
checks = [4,6] #these are the numbers to check

for chk in checks:
    for sm in  combinations(l,2):
        if chk == sum(sm): #sum(sm) means sum(1,3) for the first pass of the loop
            #Do something
-1
def summable(n, l):
    for v in l:
        l_no_v = l[:]
        l_no_v.remove(v)
        if n - v in l_no_v:
            return True
    return False

EDIT: ...

itertools.cominations - , ~ 4 , , , , .

l, l v , v (.. false false, n = 4; l = [2, 1]). v n, l, , n. , True return n, n - v.

+2

, , , x in set() .

n , , , , n - i .

- .

>>> def is_sum_of_numbers(n, numbers):
...     for i in numbers:
...         if n - i in numbers:
...             return True
...     return False
...
>>>
>>>
>>> numbers = {2,7,8,9}
>>> is_sum_of_numbers(9, numbers) # 2 + 7
True
>>> is_sum_of_numbers(5, numbers)
False
>>> is_sum_of_numbers(18, numbers) # 9 + 9
True
+1

, , , N, , N, . N, . , .

, x . , , hashset . , N-x. , , N. N-x x . , - O (1).

linear

, python , .

, , .

0

Source: https://habr.com/ru/post/1663364/


All Articles