在python 3中使用递归查找组合

时间:2013-09-16 15:33:35

标签: python python-3.x

我在使用递归查找组合时遇到问题 例如

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

1 个答案:

答案 0 :(得分: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