Addition of two sets... How to proceed

88 Views Asked by At

Consider the two sets:- {9,87} and {1,2,3,45}. Here I don't mean union but addition which shall produce the output as all possible additions of two element combos such that each element is from a different set.

So the answer I should get is:- {9+1,9+2,9+3,9+45,87+1,87+2,87+3,87+45}

How may I proceed with this type of unique addition of two sets in a continuous space? I tried with two circles and found the expression extremely difficult....

3

There are 3 best solutions below

2
John Gordon On
set3 = set()

for item1 in set1:
    for item2 in set2:
        set3.add(item1+item2)
0
BrokenBenchmark On

itertools.product can help produce the desired set. member1 is an element from set1, and member2 is an element from set2. itertools.product produces the Cartesian product of the two sets -- specifically, all possible tuples where the first element is a member of set1 and the second element is a member of set2.

import itertools

set1 = {9,87}
set2 = {1,2,3,45}
print({member1 + member2 for member1, member2 in itertools.product(set1, set2)})
0
Musa On

You can use set comprehension to achieve this

x = {9,87}
y = {1,2,3,45}
z = {i+j for i in x for j in y}