在Python中,如何在不使用遞歸和不使用itertools包的情況下編寫一個通用函數來生成重複n次的相同集的笛卡爾乘積?該函數應該有兩個參數:set和n次。Python中的笛卡爾積通用函數
如:
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'?這是功課嗎? – Blender
沒有itertools ...你用numpy好嗎? – roippi