Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a number is the sum of 2 other numbers

Tags:

python

Problem Statement

Given a list of numbers and a number k, return whether any two numbers from the list add up to k.

Example

Given [1, 2, 3] and k = 5, return True since 2 + 3 = 5.

This is what I've tried to do:

def pairs(n):
    for i in range(len(n)):
        for j in range(i+1, len()):
            yield n[i], n[j]


def ListCheck():
    number = input("Give me a number:")
    val = int(number)
    nums = [1,2,3]
    for i, j in pairs(nums):
        if j + i == val:
            print(True)
            break


ListCheck()

I'm getting an error when I run it, and I can't understand why.

like image 480
Rony Kositsky Avatar asked Jan 21 '26 10:01

Rony Kositsky


2 Answers

You could also do itertools.combinations, little shorter than @bitto's solution:

import itertools
def f(lst,num):
    for x,y in itertools.combinations(lst,2):
        if x+y==num:
            return True
    return False
lst=[1,2,3]
num=int(input("Give me a number: "))
print(f(lst,num))
like image 142
U12-Forward Avatar answered Jan 23 '26 01:01

U12-Forward


def issumoftwo(lst,num):
    for x in lst:
        for y in lst:
            if x+y==num and lst.index(x)!=lst.index(y):
                return True
    return False
lst=[1,2,3]
num=int(input("Give me a Number: "))
print(issumoftwo(lst,num))

Output

Give me a number: 5
True
like image 27
Bitto Bennichan Avatar answered Jan 22 '26 23:01

Bitto Bennichan