Thursday, March 9, 2017

Generic Cartesian Product Function

Generic Cartesian Product Function

In the following you can find a Generic Cartesian Product Function in Python.

Rem: The Cartesian product of two sets A and B (also called the product set, set direct product, or cross product) is defined to be the set of all points (a,b) where a in A and b in B. It is denoted A×B, and is called the Cartesian product since it originated in Descartes' formulation of analytic geometry. In the Cartesian view, points in the plane are specified by their vertical and horizontal coordinates, with points on a line being specified by just one coordinate. The main examples of direct products are Euclidean three-space (R×R×R, where R are the real numbers), and the plane (R×R). The graph product is sometimes called the Cartesian product (Vizing 1963, Clark and Suen 2000) [Ref: http://mathworld.wolfram.com/CartesianProduct.html].

def genericCartesianProduct(s, t):
    if t == 0:
        return set()
    result = [(e,) for e in s]
    for i in range(t - 1):
        result = [e + (f,) for e in result for f in s]
    return set(result)


example = {1, 2, 3, 4}
for i in range(4):
    print(genericCartesianProduct(example, i))


Result:
{(2,), (3,), (1,), (4,)}
{(1, 2), (3, 2), (1, 3), (4, 1), (3, 3), (3, 1), (4, 4), (2, 1), (1, 4), (2, 4), (2, 3), (4, 3), (2, 2), (4, 2), (3, 4), (1, 1)}
{(4, 3, 4), (4, 2, 2), (4, 4, 1), (1, 3, 2), (1, 4, 4), (2, 2, 4), (1, 3, 1), (4, 3, 2), (3, 3, 1), (3, 4, 1), (1, 4, 2), (4, 3, 3), (2, 4, 1), (3, 4, 2), (1, 4, 3), (2, 3, 1), (3, 3, 3), (3, 4, 3), (2, 3, 2), (4, 3, 1), (3, 3, 2), (2, 4, 3), (1, 4, 1), (2, 3, 3), (2, 4, 2), (3, 1, 4), (3, 2, 2), (4, 1, 4), (3, 3, 4), (3, 1, 3), (3, 2, 3), (2, 4, 4), (3, 1, 2), (1, 2, 1), (4, 4, 2), (3, 1, 1), (3, 2, 1), (2, 1, 4), (1, 2, 2), (1, 2, 3), (4, 1, 1), (1, 2, 4), (2, 1, 2), (4, 2, 4), (1, 1, 1), (2, 2, 3), (3, 2, 4), (2, 1, 3), (4, 1, 2), (2, 2, 2), (4, 1, 3), (1, 1, 3), (2, 2, 1), (2, 1, 1), (4, 2, 1), (1, 1, 2), (4, 4, 4), (3, 4, 4), (4, 4, 3), (1, 3, 4), (2, 3, 4), (4, 2, 3), (1, 1, 4), (1, 3, 3)}

Copyright ©2017, Software Developer, All rights reserved.
See Contents

No comments:

Post a Comment