-2

in a Multiset it is allowed to have multiple elements

For Example. if X (normal set) = {0,2,4,7,10}, then ∆X (multiset) = {2,2,3,3,4,5,6,7,8,10}.

∆X denotes the multiset of all (N 2) pairwise distances between points in X

How can i Write this in Python?

I have created a List X but i don't know how to put all differences in another list and order them.

I hope you can help me.

  • 2
    Welcome to Stack Overflow! You seem to be asking for someone to write some code for you. Stack Overflow is a question and answer site, not a code-writing service. Please [see here](http://stackoverflow.com/help/how-to-ask) to learn how to write effective questions. – Derek Brown Apr 23 '18 at 18:00
  • https://docs.python.org/3/tutorial/index.html – wwii Apr 23 '18 at 18:26

3 Answers3

1

It is basically just one line.

import itertools

s = {0,2,4,7,10}
sorted([abs(a-b) for (a,b) in itertools.combinations(s,2)])
pault
  • 41,343
  • 15
  • 107
  • 149
PEZO
  • 441
  • 4
  • 14
0

A simple way is to convert your set to a list, sort it, and then use a double for loop to compute the differences:

X = {0,2,4,7,10}  # original set
sorted_X = sorted(list(X))
diffs = []
for i, a in enumerate(sorted_X):
    for j, b in enumerate(sorted_X):
        if j > i:
            diffs.append(b-a)           
print(diffs)
#[2, 4, 7, 10, 2, 5, 8, 3, 6, 3]

And if you want the diffs sorted as well:

print(sorted(diffs))
#[2, 2, 3, 3, 4, 5, 6, 7, 8, 10]

Another option that would work in this case is to use itertools.product:

from itertools import product
print(sorted([(y-x) for x,y in product(sorted_X, sorted_X) if y>x]))
#[2, 2, 3, 3, 4, 5, 6, 7, 8, 10]
pault
  • 41,343
  • 15
  • 107
  • 149
0

you can use itertools

import itertools

s = {0,2,4,7,10}
k = itertools.combinations(s,2)
distance = []
l = list(k)
for p in l:
    distance.append(abs(p[1]-p[0]))
print(sorted(distance))
Morpheus
  • 3,285
  • 4
  • 27
  • 57