gpt4 book ai didi

python - Python 中的笛卡尔积通用函数

转载 作者:行者123 更新时间:2023-11-30 23:34:54 32 4
gpt4 key购买 nike

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

例如:

set1={'a','b'}
print({(x,y) for x in set1 for y in set1})

{('a', 'b'), ('b', 'a'), ('b', 'b'), ('a', 'a')}

print({(x,y,z) for x in set1 for y in set1 for z in set1})

{('b', 'a', 'b'), ('a', 'b', 'a'), ('a', 'a', 'a'), ('b', 'a', 'a'), ('a', 'a', 'b'), ('b', 'b', 'a'), ('b', 'b', 'b'), ('a', 'b', 'b')}

等等

而且:

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)])

关于python - Python 中的笛卡尔积通用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17763862/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com