I have a homework problem that requires me to write a function that given an integer k
and a list of n unordered integers A
, determines if there is a distinct pair of integers in A
that sum to k
.
I'm struggling to get the function to evaluate all possible combinations of the values in the list. As soon as it gets a pair that does not sum to k it stops. If anyone has any suggestions / tips, I'd greatly appreciate it. I'm not looking for the outright answer, just a nudge in the right direction.
Here is what I have so far:
def sumsToK(k, list1):
newSet = set(list1) #creates set based on list1 to remove any duplicate values
print (newSet)
newSet = list(newSet) #convert back to list so I can iterate through values
for i in range(len(newSet)):
for j in range(i 1, len(newSet)):
print(newSet[i],newSet[j])
if (newSet[i]) (newSet[j]) == k:
return (print('There is at least one pair if integers that adds up to k'))
else:
return(print('There are is no pair of distinct integers that adds up to k'))
k = 9
list1 = [1, 2, 3, 4, 5, 5, 5, 6, 7, 8, 9, 10] #Multiple distinct pairs will sum to 9
print ((sumsToK(k, list1)))
CodePudding user response:
As soon as it gets a pair that does not sum to k it stops
That's normal given your code: you return immediately at the first iteration, whether you did find a pair or did not find a pair.
Remove the second return and you are all set:
def sumsToK(k, list1):
newSet = set(list1) #creates set based on list1 to remove any duplicate values
print (newSet)
newSet = list(newSet) #convert back to list so I can iterate through values
for i in range(len(newSet)):
for j in range(i 1, len(newSet)):
print(newSet[i],newSet[j])
if (newSet[i]) (newSet[j]) == k:
return('There is at least one pair if integers that adds up to k')
else:
# it's important not to return anything here otherwise you
# exit the loop :)
print('This is not a pair of distinct integers that adds up to k')
k = 9
list1 = [1, 2, 3, 4, 5, 5, 5, 6, 7, 8, 9, 10] #Multiple distinct pairs will sum to 9
print ((sumsToK(k, list1)))
It gives me:
set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
(1, 2)
(1, 3)
(1, 4)
(1, 5)
(1, 6)
(1, 7)
(1, 8)
There is at least one pair if integers that adds up to k
By the way, do not return print
statements, just return the string, or print
it (not both!).