The following function sum_pairs(ints, s)
takes two inputs: ints
is a list with integer values and s
is a integer number. The function sum_pairs
returns the values (x, y)
in ints
such that \$s = x + y\$ and the index of y
is the lowest for the (x, y)
in ints
such that \$s = x + y\$. This is a problem taken from codewars. The function passes all the test cases. However, when I attempt to run the code for a big list, the server codewars gives me the following answer: "Process was terminated. It took longer than 12000ms to complete".
I am wondering whether the code I have written to solve the problem can be optimised or should I use a different approach to give a solution.
def sum_pairs(ints, s):
begin = 1
end = len(ints)
memo = []
while begin < end:
try:
memo.append([begin-1, ints.index(s - ints[begin-1], begin, end)])
begin += 1
end = memo[-1][1]
except:
begin +=1
if memo == []:
return None
else:
return [ints[memo[-1][0]], ints[memo[-1][1]]]
The function sum_pairs(ints, s)
searches for \$y = s - x\$ in the list ints
using the function index()
. If a value of y
is found the index for the pair (x,y)
is added to memo
, then the range for the search (begin, end)
are updated. Else only the lower limit begin
for the search is updated.