How to check if a sum of one pair of a factor is equal to the difference of another pair?
Solution 1:
Try to use itertools.combinations
:
from itertools import combinations
x = # your number
for p1, p2 in combinations(Factors(x), 2):
if sum(p1) == abs(p2[0] - p2[1]) or sum(p2) == abs(p1[0] - p1[1]):
print(p1, p2)
This is a solution implementing a great suggestion from @ScottHunter (its complexity is O(n)):
x = # this is your number, 6 for example
f = Factors(x)
dct = {}
for p in f:
s = sum(p)
if s in dct:
dct[s].append(p)
else:
dct[s] = [p]
for p1 in f:
d = abs(p1[0] - p1[1])
if d in dct:
print(*((p1, p2) for p2 in dct[d]))
How does this work? First you build a dictionary which maps a sum of factors to a list of pairs that sum up to that value. For example here f1 + f2 == f3 + f4 == k
:
dct = {k: [(f1, f2), (f3, f4)]}
Then you iterate over your pairs of factors, find their difference (with d = abs(p[0] - p[1])
). Now, if their is a pair (x1, x2)
whose difference d
is equal to the sum of another pair (x3, x4)
then for sure (x3, x4)
can be found in dct[d]
.
Solution 2:
You can compare each pair with each other. There is a convenient function in the itertools
module, which is part of the python standard library. Try
import itertools as it
for (p1,p2),(q1,q2) in it.permutations(Factors(x),2):
if p1+p2 == abs(q1-q2):
print('{} + {} == |{} - {}|'.format(p1,p2,q1,q2)