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.
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))
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With