Lokesh Meher - 1 year ago 37

Python Question

I want to calculate absolute difference between all elements in a set of integers. I am trying to do

`abs(x-y)`

`x`

`y`

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

Source (Stackoverflow)