【发布时间】:2013-07-19 18:55:04
【问题描述】:
在 Python 中,如何编写一个通用函数来生成重复 n 次的同一集合的笛卡尔积而不使用递归和不使用 itertools 包?该函数应该有两个参数:集合和n次。
例如:
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})
等等
【问题讨论】:
-
为什么不能使用
itertools?这是作业吗? -
没有 itertools... 你对 numpy 还好吗?
标签: python for-loop set cartesian-product