[英]Recursively generate combinations with Python
我正在尝试提供一种递归方法,当给出课程列表时,该方法将提供所有可能组合的列表。 例如课程= [主菜,甜点]这是我到目前为止的内容:
Entree = ["pumkinsoup","antipasto"]
Dessert = ["cheesecake", "icecream", "tiramisu", "cheeseplatter"]
courses = [Entree, Dessert]
def make_orders(courses):
dishes_so_far = []
recursive_make_orders(dishes_so_far, courses)
def recursive_make_orders(dishes_so_far, courses):
n = len(courses)
if n==0 :
print(dishes_so_far)
else:
current_courses = courses[0]
for D in current_courses:
dishes_so_far.append(D)
recursive_make_orders(dishes_so_far , courses[1:len(courses)])
\\我正在尝试使其打印出[[pumkinsoup,cheesecake],[punkinsoup, icecream]]
等组合,但实际上它给了我[pumkinsoup, cheesecake, icecream]
等。
尝试用加法而不是追加来添加它,这给了我一个错误。
这是家庭作业,因此需要递归方法。
您距离不太远-使用itertools.product
和*courses
进行解压缩:
from itertools import product
for course in product(*courses):
print course
('pumkinsoup', 'cheesecake')
('pumkinsoup', 'icecream')
('pumkinsoup', 'tiramisu')
('pumkinsoup', 'cheeseplatter')
('antipasto', 'cheesecake')
('antipasto', 'icecream')
('antipasto', 'tiramisu')
('antipasto', 'cheeseplatter')
如果要使用递归版本,可以执行以下操作:
def worker(entree, dessert):
d = []
if not entree or not dessert: return d
d.append((entree[0], dessert[0]))
d += worker(entree[1:], dessert)
d += worker(entree, dessert[1:])
return d
您的版本无法正常运行,因为courses
现在是列表列表,而courses[0]
只是Entree
,因此您需要从Entree
递归构造新列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.