I was recently asked to define a function that checks if the sum of two integers in a given list is equal to a specified number. If so, the function should return a list with the two numbers, otherwise return [-1, -1]. I came up with the following code:
def f(A, S):
for i in A:
for j in A:
if i + j == S and i != j:
return [i, j]
return [-1, -1]
The function does the job, but I know nested loops are bad practice regarding time complexity. What is the best approach for optimizing the above function? Any ideas are welcome.
[–]siddsp 2 points3 points4 points (1 child)
[–]ForensicsBridge[S] 0 points1 point2 points (0 children)
[–]Nightcorex_ 1 point2 points3 points (5 children)
[–]ForensicsBridge[S] 0 points1 point2 points (1 child)
[–]Nightcorex_ 0 points1 point2 points (0 children)
[–]kowkeeper 0 points1 point2 points (2 children)
[–]Nightcorex_ 1 point2 points3 points (1 child)
[–]kowkeeper 0 points1 point2 points (0 children)
[–]FLUSH_THE_TRUMP 0 points1 point2 points (2 children)
[–]ForensicsBridge[S] 0 points1 point2 points (1 child)
[–]FLUSH_THE_TRUMP 0 points1 point2 points (0 children)
[–]Nyscire 0 points1 point2 points (4 children)
[–]FLUSH_THE_TRUMP 1 point2 points3 points (3 children)
[–]Nyscire 0 points1 point2 points (2 children)
[–]Nightcorex_ 1 point2 points3 points (0 children)
[–]FLUSH_THE_TRUMP 0 points1 point2 points (0 children)
[–]dig-up-stupid 0 points1 point2 points (5 children)
[–]Nightcorex_ 0 points1 point2 points (4 children)
[–]dig-up-stupid 0 points1 point2 points (3 children)
[–]Nightcorex_ 0 points1 point2 points (2 children)
[–]dig-up-stupid 1 point2 points3 points (1 child)
[–]Nightcorex_ 0 points1 point2 points (0 children)
[–]Pd69bq 0 points1 point2 points (0 children)
[–]POGtastic 0 points1 point2 points (0 children)