Skip to content Skip to sidebar Skip to footer

Python: Calculate Difference Between All Elements In A Set Of Integers

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 c

Solution 1:

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 incombinations(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)]

Solution 2:

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

Solution 3:

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}

Solution 4:

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"

Solution 5:

Here is another way using combinations:

from itertools import combinations

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

  returnmin(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

Post a Comment for "Python: Calculate Difference Between All Elements In A Set Of Integers"