Lokesh Meher Lokesh Meher - 5 months ago 9
Python Question

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 combinations and save the resulting list in a new set.

Answer

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