I want make a program that calculates the cartesian products of two sets. e.g.:

This is how i would like the result to look like:
>>>
Enter two sets to calculate the cartesian product: set([7,9]), set([1,5])
set([(7,1),(9,1),(7,5),(9,5)])

def main():
    userinput = input('Enter two sets to calculate the cartesian product: ')
    set1, set2 = userinput.split(',')
    myset1 = eval(set1.strip())
    myset2 = eval(set2.strip())
    ...?

main()

I've now made a function who you now can insert two sets in the function and the function will make the two sets from being two 'str' to two 'set'. Now I would like the first element in the first set to pair up with the first element in the second set, then the second element in the first set to pair up with the first element in the second set and so forth.. I think you get the point. The problem is that I dont know how to make python do this.
:X Please help me

Recommended Answers

All 4 Replies

It already exists (py >= 2.6)

from itertools import product
myproduct = set(product(myset1, myset2))
Member Avatar

...or... you could try something like this

def cartesianProduct( set1, set2 ):
    l = []
    for i in set1:
        for j in set2:
            l += [ ( i, j ) ]
    print l

cartesianProduct( [ 1, 2, 3 ], [ "a", "b", "c" ] )

>>> 
[(1, 'a'), (1, 'b'), (1, 'c'), (2, 'a'), (2, 'b'), (2, 'c'), (3, 'a'), (3, 'b'), (3, 'c')]
>>>

Thanks guys. This solves it :)

product = set( ( i, j ) for i in set1 for j in set2 )
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.