我寫了下面的遞歸例程來計算兩個集合的交叉乘積。使用遞歸的集合的交叉積
def combine(input1,input2,output):
if len(input2)==0:
return output
else:
for num in input1:
output.append((num,input2[0]))
combine(input1,input2[1:],output)
input1=[1 2 5]
input2=[2 3]
output=[(1,2), (1,3), (2,2),(2,3),(5,2),(5,3)]
是否有可能使遞歸更好,例如刪除其他循環,並試圖在相同的功能。我正在尋找解決問題的不同方法。
編輯:不尋找與內置東西的解決方案。尋找如何以不同方式進行遞歸,而不是使用itertools.product。
你知道'itertools.product'嗎? – 2013-02-26 21:33:32
@LevLevitsky我的不好,編輯了這個問題 – gizgok 2013-02-26 21:34:54
我想你最後的'combine'調用需要在它前面有一個'return'。 – DSM 2013-02-26 21:37:50