簡體   English   中英

遞歸python函數的輸出

[英]Output of recursive python function

我的函數有問題,該函數應在列表中返回所有可能的組合,而無需重復示例。

該功能運行完美,但我無法獲得所有組合的列表:

abc = ['a','b','c','d','e']

def combi(pre, listg, stage=1,first = 1):
    if len(listg)==0:
        return []
    start = first
    lifeat =[]
    for i in range(start,len(listg)):
        lifeat.append(pre + [listg[i]])
        print('stage: ',stage,'|| ',i,' ',pre + [listg[i]])
        diff = set(listg[i:]) - set(pre+[listg[i]])
        seted= [item for item in listg[i:] if item in diff]
        li = combi(pre+ [listg[i]],seted,stage+1, first= 0)
        #print('li : ',li)
    return lifeat+li


def all_combi(liste):
    return combi([liste[0]], liste)
all_combi(abc)

打印結果: print('stage: ',stage,'|| ',i,' ',pre + [listg[i]])

stage:  1 ||  1   ['a', 'b']
stage:  2 ||  0   ['a', 'b', 'c']
stage:  3 ||  0   ['a', 'b', 'c', 'd']
stage:  4 ||  0   ['a', 'b', 'c', 'd', 'e']
stage:  3 ||  1   ['a', 'b', 'c', 'e']
stage:  2 ||  1   ['a', 'b', 'd']
stage:  3 ||  0   ['a', 'b', 'd', 'e']
stage:  2 ||  2   ['a', 'b', 'e']
stage:  1 ||  2   ['a', 'c']
stage:  2 ||  0   ['a', 'c', 'd']
stage:  3 ||  0   ['a', 'c', 'd', 'e']
stage:  2 ||  1   ['a', 'c', 'e']
stage:  1 ||  3   ['a', 'd']
stage:  2 ||  0   ['a', 'd', 'e']
stage:  1 ||  4   ['a', 'e']

這是我得到的輸出: 輸出

[['a', 'b'], ['a', 'c'], ['a', 'd'], ['a', 'e']]

預先感謝您的任何幫助。

您的邏輯中有幾個問題。 我強烈建議您使用增量編程來解決您的困難。

  1. 您假定第一個元素是每個組合的必需成員。
  2. 您只能在for循環中附加li的最后一個值; lifeat應該讓他們全部。

對於第二個問題,將return語句更改為兩行:

    lifeat += li
return lifeat

這可以改善您的結果

[['a', 'b'], ['a', 'b', 'c'], ['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd', 'e'],
 ['a', 'b', 'c', 'e'], ['a', 'b', 'd'], ['a', 'b', 'd', 'e'], ['a', 'b', 'e'],
 ['a', 'c'], ['a', 'c', 'd'], ['a', 'c', 'd', 'e'], ['a', 'c', 'e'], ['a', 'd'],
 ['a', 'd', 'e'], ['a', 'e']]

我將初始化問題留給您。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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