I came up with two solutions.
The first one, which am pretty sure is the one what you are being asked for, does all the possible sums -worst case scenario- with only one pass:
def verify_2(l,k):
i = 0
j = 0
n = len(l)
while i < n - 1:
j = i + 1
while j < n:
if l[i] + l[j] == k:
return True
j = j + 1
i = i + 1
return False
print(verify_2(l = [10,15,3,7], k = 17)) #RETURNS TRUE
print(verify_2(l = [10,15,3,7], k = 6)) #RETURNS FALSE
The other one is less efficient (because it has to sort the vector firt, which already has n*log(n)
complexity at the very least), and you have to manually do another pass. This is NOT what you are being asked for, but since it is easier to understand I leave it to you as well:
def verify(l,k):
l.sort()
for i in range(len(l) - 1):
if l[i] + l[i+1] == k:
return True
return False
print(verify(l = [10,15,3,7], k = 17)) #RETURNS TRUE
print(verify(l = [10,15,3,7], k = 6)) #RETURNS FALSE
P.S.1 First solution is WAY faster than the second one.
P.S.2 Regarding your solution I have to tell you several things. Avoid using the word "list" for variables or parameters, since it is a word of the Python language that is reserved for converting another datatype to the datatype "list" (i.e. if you have s = "hello"
and you do s = list(s)
then you get that s has['h','e','l','l','o']
inside). Also bare in mind that all the code BELOW the function header (below def...) NEEDS to be indented, either with four spaces, two spaces or one tab (or you get an interpretation error). You also should note that in your solution k
is used, but it is not a defined variable; you should pass it as a parameter or define it inside the function, or you cannot work with it (former is advised, not latter). Even accounting for that, your function did not do what was asked in the text: It actually subtracts the i-th element from k at each step of the for loop, and checks at each iteration whether the result of the subtraction belongs to the list.