簡體   English   中英

用Python遞歸生成組合

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM