2013-09-16 24 views
-1

我有發現使用遞歸 例如組合麻煩在python使用遞歸查找組合3

a = ['a', 'b','c'], 
b = ['d','e','f'] 
c = ['g','h','i'] 

輸入A,B,C 有27個可能的組合

combinations = [] 
if string == "": 
    print (combinations) 
    return 
else: 
    for i in string.head(): 
     recursive_combinations(combinations , string.tail()) 
+0

請發佈您的代碼,以便我們可以看看迄今爲止所做的工作。 :) – Talvalin

回答

3

的最簡單,慣用的方式是使用itertools,而不是遞歸。像這樣:

import itertools as it 

v1 = ['a', 'b','c'] 
v2 = ['d','e','f'] 
v3 = ['g','h','i'] 

list(it.product(v1, v2, v3)) 
=> ... the cartesian product of the input lists ... 

len(list(it.product(v1, v2, v3))) 
=> 27