I come from a C++/Java background and have done a simple implementation of the 'TwoNumberSum' algorithm below. I first implemented it in a more C/Java way using the conventional nested loop then using the 'in' operator. I was expecting both to execute in similar time as 'in' should ideally also iterate through the list which should result in a nested loop and thus somewhere similar execution time but to my surprise the first algorithm takes double the time of the second. Can someone explain what is causing such huge gap in runtime?
I am getting below results on executing the snippet.
Execution Time of Algo 1: 1.023191
Execution Time of Algo 2: 0.46218059999999994
from timeit import timeit
# First Algorithm using simple lists/arrays
code1 = """
def TwoNumberSum(list, sum):
for i in range(0, len(list)-1):
for j in range(i+1, len(list)):
if list[i] + list[j] == sum:
return [list[i], list[j]]
return []
TwoNumberSum([3, 5, -4, 8, 11, 1, -1, 6], 10)
"""
# Second Algorith similar to first using 'in' operator
code2 = """
def TwoNumberSum(list, sum):
for i in range(0, len(list)-1):
if sum-list[i] in list[i+1:-1]:
return [list[i], sum-list[i]]
return []
TwoNumberSum([3, 5, -4, 8, 11, 1, -1, 6], 10)
"""
print(f"Execution Time of Algo 1: {timeit(code1, number=100000)}")
print(f"Execution Time of Algo 2: {timeit(code2, number=100000)}")