Thank you for clearly defining your question and for providing your code
example that you are attempting to optimize.
Utilizing two key definitions from your question and the notation you
provided, I limited my optimization attempt to the use of lists, and added
the ability to randomly change the values associated to n, a1, b1, a2 and
b2.
In order to show the optimization results, I created a module which includes
the use of the random.randit function to create a variety of list sizes and
the timeit.Timer function to capture the amount of time your original pairs() function takes as well as my suggested optimization in the the pairs2() function.
In the pairs2() function, you will note that each iteration loop contains a
break statement. These eliminate needless iteration through each list once
the desired criteria is met. You should note that as the size of the lists
grow, the pairs2() vs. pairs() time improves.
Test module code:
import random
from timeit import Timer
max_value = 10000
n = random.randint(1, max_value)
a1 = random.randint(0, max_value)
b1 = random.randint(1, max_value+1)
a2 = random.randint(0, max_value)
b2 = random.randint(1, max_value+1)
if b1>n:
b1=n
if b2>n:
b2=n
if a1>=b1:
a1 = random.randint(0, b1-1)
if a2>=b2:
a2 = random.randint(0, b2-1)
diap1 = [x for x in range(a1, b1)]
diap2 = [x for x in range(a2, b2)]
print("Length diap1 =", len(diap1))
print("Length diap2 =", len(diap2))
def pairs(d1, d2, n):
res = 0
same = 0
sl1 = sorted(d1)
sl2 = sorted(d2)
for i in sl1:
for j in sl2:
if i+j==n and i!=j:
res+=1
elif i+j==n and i==j:
same+=1
return(res+same)
def pairs2(d1, d2, n):
res = 0
same = 0
sl1 = sorted(d1)
sl2 = sorted(d2)
for i in sl1:
for j in sl2:
if i+j==n and i!=j:
res+=1
break
elif i+j==n and i==j:
same+=1
break
if res+same>0:
break
return(res+same)
if __name__ == "__main__":
result=0
timer = Timer("result = pairs(diap1, diap2, n)",
"from __main__ import diap1, diap2, n, pairs")
print("pairs_time = ", timer.timeit(number=1), "result =", result)
result=0
timer = Timer("result = pairs2(diap1, diap2, n)",
"from __main__ import diap1, diap2, n, pairs2")
print("pairs2_time = ", timer.timeit(number=1), "result =", result)