Lokesh Meher - 1 year ago 63

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`

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

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

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**