Thank you for clearly defining your question and for providing the code with an example that you are trying to optimize.
Using two key definitions from your question and notation you provided that I limited my attempt to optimize the use of lists and added the ability to randomly change the values ​​associated with n, a1, b1, a2 and b2.
To show the results of the optimization, I created a module that includes using the random.randit function to create different list sizes and the timeit.Timer function to fix the amount of time that your original pair () takes, as well as my proposed optimization in pairs2 () function .
In the pairs2 () function, you will notice that each iteration loop contains break. They eliminate unnecessary iteration through each list once the required criteria are met. It should be noted that the size of the lists is increasing, the number of pairs2 () is increasing compared to pairs ().
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)