Python: Calculate difference between all elements in a set of integers

Question:

I want to calculate absolute difference between all elements in a set of integers. I am trying to do abs(x-y) where x and y are two elements in the set. I want to do that for all combinations and save the resulting list in a new set.

Asked By: Lokesh Meher

||

Answers:

As sets do not maintain order, you may use something like an ordered-set and iterate till last but one.

Answered By: Siva Umapathy

I want to calculate absolute difference between all elements in a set of integers (…) and save the resulting list in a new set.

You can use itertools.combinations:

s = { 1, 4, 7, 9 }
{ abs(i - j) for i,j in combinations(s, 2) }
=>
set([8, 2, 3, 5, 6])

combinations returns the r-length tuples of all combinations in s without replacement, i.e.:

list(combinations(s, 2))
=>
[(9, 4), (9, 1), (9, 7), (4, 1), (4, 7), (1, 7)]
Answered By: miraculixx

For completeness, here’s a solution based on Numpy ndarray‘s and pdist():

In [69]: import numpy as np

In [70]: from scipy.spatial.distance import pdist

In [71]: s = {1, 4, 7, 9}

In [72]: set(pdist(np.array(list(s))[:, None], 'cityblock'))
Out[72]: {2.0, 3.0, 5.0, 6.0, 8.0}
Answered By: Tonechas

Here is another solution based on numpy:

data = np.array([33,22,21,1,44,54])

minn = np.inf
index = np.array(range(data.shape[0]))
for i in range(data.shape[0]):
    to_sub = (index[:i], index[i+1:])
    temp = np.abs(data[i] - data[np.hstack(to_sub)])
    min_temp = np.min(temp)
    if min_temp < minn : minn = min_temp
print('Min difference is',minn)

Output: “Min difference is 1”

Answered By: Alberto Lanaro

Here is another way using combinations:

from itertools import combinations

def find_differences(lst):
  " Find all differences, min & max difference "
  d = [abs(i - j) for i, j in combinations(set(lst), 2)]

  return min(d), max(d), d

Test:

list_of_nums = [1, 9, 7, 13, 56, 5]
min_, max_, diff_ = find_differences(list_of_nums)
print(f'All differences: {diff_}nMaximum difference: {max_}nMinimum difference: {min_}')

Result:

All differences: [4, 6, 8, 12, 55, 2, 4, 8, 51, 2, 6, 49, 4, 47, 43]
Maximum difference: 55
Minimum difference: 2
Answered By: Michael
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.