Reputation: 159
"""
Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.
"""
numbers = [7, 15, 17]
k = 14
def add_to_k(numbers_list,k_value):
truth = False
for i in numbers_list:
for l in numbers_list:
added = i + l
if added == k_value:
num1 = i
num2 = l
truth = True
if truth == True:
print("Two numbers in the list added together is 17. " + str(num1) + " " + str(num2))
else:
print("Sorry, none give " + str(k_value))
add_to_k(numbers,k)
Following the prompt in the comments above, I made my attempt at this challenge. However, I realized that it would add the first number of the list twice, though I want to find two separate numbers that would add up to k. How would I go about changing this code? Thank you!
Upvotes: 0
Views: 190
Reputation: 41872
Let's try a simple approach with no additional libraries. But we will exploit Python's new walrus :=
operator:
def add_to_k(numbers, k):
pairs = []
while numbers:
if (b := k - (a := numbers.pop())) in numbers:
pairs.append((a, b))
numbers.remove(b)
return pairs
if __name__ == "__main__":
numbers = [10, 15, 2, 7]
k = 17
if pairs := add_to_k(numbers, k):
for pair in pairs:
print("{} + {} = {}".format(*pair, k))
else:
print("Sorry, no solution for {}".format(k))
OUTPUT
> python3 test.py
7 + 10 = 17
2 + 15 = 17
>
In addition to finding multiple solutions if they exist, the result of this add_to_k()
can also be treated as a boolean to say whether any solution exists. This solution should handle problems like k = 18
and numbers = [9, 9]
vs. numbers = [9]
correctly.
Upvotes: 0
Reputation: 6483
You should iterate over the array without the element that is being tested:
numbers = [7, 7, 17]
k = 14
def add_to_k(numbers_list,k_value):
truth = False
for i in numbers_list:
y = numbers_list[:] # fastest way to copy
y.remove(i)
for l in y:
added = i + l
if added == k_value:
num1 = i
num2 = l
truth = True
if truth == True:
print("Two numbers in the list added together is "+str(k_value)+ ": " + str(num1) + "," + str(num2))
else:
print("Sorry, none give " + str(k_value))
add_to_k(numbers,k)
Output:
Two numbers in the list added together is 14: 7,7
Or if want another option:
import itertools as it
numbers = [12, 7, 17]
k = 19
def add_to_k(numbers_list,k_value):
results = {i:sum(i) for i in list(it.combinations(numbers_list, 2))}
if any(val==k_value for val in results.values()):
print(f'Two numbers in the list added together is {k_value}:{list(results.keys())[list(results.values()).index(k_value)] }')
else:
print(f'Sorry, none give {k_value}')
add_to_k(numbers,k)
Output
Two numbers in the list added together is 19:(12, 7)
Upvotes: 3
Reputation: 27567
You can use combinations
from itertools
:
from itertools import combinations
numbers = [7, 15, 17, 10, 4]
k = 14
for t in combinations(numbers,2):
if sum(t)==k:
print(f"Two numbers in the list added together is {k}. {t[0]} {t[1]}")
break
else:
print(f"Sorry, none give {k}")
Output:
Two numbers in the list added together is 14. 10 4
Upvotes: 1