How to find all those triplets points which are present at equidistant from each other in python

Viewed 34

i am solving a basic python problem,my task is to find all those triplets points which are at equidistant from each other. for example

points=[1,2,4,6,7,8]
res=[(1,4,7),(2,4,6),(4,6,8),(6,7,8)]

explanation:

(1,4,7)->  4-1 is equals to 7-4
(2,4,6)->  4-2 is equals to 6-4

and so on..

2 Answers

Try this:

from itertools import combinations

res = []
for vals in combinations(points, 3):
    p1, p2, p3 = sorted(vals)
    if p2 - p1 == p3 - p2:
        res.append((p1, p2, p3))

Here is the result:

>>> res
[(1, 4, 7), (2, 4, 6), (4, 6, 8), (6, 7, 8)]

Tried to do without libraries. First, a dictionary is created, where the keys are the difference between all pairs of numbers from the list, and the pairs as a set are placed in the list associated with the key. In the second phase, all collected pairs in the list of one key are checked for intersection. If a common element is found, the union of the sets is entered into the resulting list.

points = [1, 2, 4, 6, 7, 8]

d = {}
for n, i in enumerate(points):
    for j in points[n + 1:]:
        d.setdefault(abs(i - j), []).append({i, j})

out = []
for el in d.values():
    for n, i in enumerate(el):
        for j in el[n + 1:]:
            if i.intersection(j):
                out.append(i.union(j))
print(out)
[{8, 6, 7}, {1, 4, 7}, {2, 4, 6}, {8, 4, 6}]
Related