Python中的笛卡尔乘积泛型函数

Python中的笛卡尔乘积泛型函数,python,for-loop,set,cartesian-product,Python,For Loop,Set,Cartesian Product,在Python中,我如何编写一个泛型函数来生成相同集合的笛卡尔积重复n次,而不使用递归和itertools包?该函数应采用两个参数:set和n次 e、 g: 等等 而且: set2={'a','b','c'} print({(x,y,z) for x in set2 for y in set2 for z in set2}) print({(w,x,y,z) for w in set2 for x in set2 for y in set2 for z in set2}) 等等。你可以通过反复

在Python中,我如何编写一个泛型函数来生成相同集合的笛卡尔积重复n次,而不使用递归和itertools包?该函数应采用两个参数:set和n次

e、 g:

等等

而且:

set2={'a','b','c'}
print({(x,y,z) for x in set2 for y in set2 for z in set2})
print({(w,x,y,z) for w in set2 for x in set2 for y in set2 for z in set2})

等等。

你可以通过反复构建结果来概括你已经在使用的基于理解的技巧:

   def cartesian_product(s, dim):
        if dim == 0:
            return set()
        res = [(e,) for e in s]
        for i in range(dim - 1):
            res = [e + (f,) for e in res for f in s]
        return set(res)

    ex = {1,2,3}

    for i in range(4):
        print cartesian_product(ex, i)
输出:

set([])
set([(2,), (3,), (1,)])
set([(1, 2), (3, 2), (1, 3), (3, 3), (3, 1), (2, 1), (2, 3), (2, 2), (1, 1)])
set([(1, 3, 2), (1, 3, 1), (3, 3, 1), (2, 3, 1), (3, 3, 3), (2, 3, 2), (3, 3, 2), (2, 3, 3), (3, 2, 2), (3, 1, 3), (3, 2, 3), (3, 1, 2), (1, 2, 1), (3, 1, 1), (3, 2, 1), (1, 2, 2), (1, 2, 3), (1, 1, 1), (2, 1, 2), (2, 2, 3), (2, 1, 3), (2, 2, 2), (2, 2, 1), (2, 1, 1), (1, 1, 2), (1, 1, 3), (1, 3, 3)])

我想你是在寻找所谓的“一套”的概念

我不知道为什么你不能使用
itertools
,但我认为应该用一个例子来指出这一点,即使你不使用它,也可以采取安全措施

>>> import itertools
>>> set1 = {'a', 'b'}
>>> list(itertools.product(set1, repeat=0))
[()]
>>> list(itertools.product(set1, repeat=1))
[('a',), ('b',)]
>>> list(itertools.product(set1, repeat=2))
[('a', 'a'), ('a', 'b'), ('b', 'a'), ('b', 'b')]
当您需要模拟n个嵌套for循环时,递归非常方便

def cartesian_power(seq, p):
    if p == 0:
        return [()]
    else:
        result = []
        for x1 in seq:
            for x2 in cartesian_power(seq, p - 1):
                result.append((x1,) + x2)
        return result


为什么不能使用
itertools
?这是家庭作业吗?没有工具。。。你同意numpy吗?这正是我想要的,也让我意识到在Python中,单元素元组需要一个尾随逗号。
>>> import itertools
>>> set1 = {'a', 'b'}
>>> list(itertools.product(set1, repeat=0))
[()]
>>> list(itertools.product(set1, repeat=1))
[('a',), ('b',)]
>>> list(itertools.product(set1, repeat=2))
[('a', 'a'), ('a', 'b'), ('b', 'a'), ('b', 'b')]
def cartesian_power(seq, p):
    if p == 0:
        return [()]
    else:
        result = []
        for x1 in seq:
            for x2 in cartesian_power(seq, p - 1):
                result.append((x1,) + x2)
        return result
>>> cartesian_power([1, 2], 0)
[()]
>>> cartesian_power([1, 2], 1)
[(1,), (2,)]
>>> cartesian_power([1, 2], 2)
[(1, 1), (1, 2), (2, 1), (2, 2)]
>>>