简体   繁体   中英

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:

  • aa[first] does not start at 1
  • my second array keeps getting smaller when the size should always be 8. Hence, giving me the error "IndexError: list index out of range"
  • it doesn't stop when it finds a sum

Any help would be great

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

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