hon kon
hon kon

Reputation: 9

Python find sum of two numbers from list

I am trying to write some code to check if a number is a sum of any two numbers in a list/dictionary and if a number is found, it stops running. However, I am running into some errors. Maybe my logic is wrong but here is my code:

a = [1,2,3,4,5,6,7,8,9]

randomNumber = 8

print len(a)
length_of_a = len(a)
for first in range(0,length_of_a -1):
    aa = a
    bb = a
    del bb[first]
    length_of_b = len(bb)
    print bb, length_of_b
    for second in range(0, length_of_b-1):
        print aa[first], bb[second]
        x = aa[first] + bb[second]
        print x
        if x == randomNumber:
            print "Sum Found!"
            break
        else:
            print "No Sum"

So my errors:

Any help would be great

Upvotes: 0

Views: 2095

Answers (1)

zondo
zondo

Reputation: 20336

There is a very simply way to do what you want. It's one line, so you can define it with a lambda function:

is_sum = lambda seq, x: any(x == y + z for yi, y in enumerate(seq) for zi, z in enumerate(seq) if zi != yi)

To use:

>>> is_sum([1, 2, 3, 4], 5)
True
>>> is_sum([1, 2, 3, 4], 6)
True
>>> is_sum([1, 2, 3, 4], 12)
False

Upvotes: 3

Related Questions