簡體   English   中英

Python3 遞歸,for 循環,函數返回奇怪的輸出

[英]Python3 recursive, for-loop, function returns strange output

我的函數combinations(ary, p)被假定return列表中項目順序的每個可能的組合 但它總是多次返回第一個值,即使它找到了所有可能的訂單,我知道這是因為它會打印它們。
編輯:我想讓它自己工作,學習一些東西而不使用任何外部庫。

def combinations(ary, p):
    ln = len(ary)
    bary=[]
    for a in range(ln-p):
        if p<ln-2:
            bb = combinations(ary, p+1)
            for be in bb:
                bary.append(be)
        if p>=ln-2:
            bary.append(ary)
        ary.append(ary.pop(p))
    return bary


另一個帶有調試 print() 函數的版本。 我將給出它的示例輸出。

def combinations(ary, p):
    ln = len(ary)
    bary=[]
    for a in range(ln-p):
        if p<ln-2:
            bb = combinations(ary, p+1)
            for be in bb:
                bary.append(be)
        if p>=ln-2:

    -->     bary.append(ary)
    -->     print('ary', ary, 'bary', bary)

        ary.append(ary.pop(p))
    return bary

使用combinations([7,3,2], 0):運行后的控制台輸出::

##  There is clearly every possible combination:
##
##      ||
##      ||
        \/
ary [7, 3, 2] bary [[7, 3, 2]]
ary [7, 2, 3] bary [[7, 2, 3], [7, 2, 3]]
ary [3, 2, 7] bary [[3, 2, 7]]
ary [3, 7, 2] bary [[3, 7, 2], [3, 7, 2]]
ary [2, 7, 3] bary [[2, 7, 3]]
ary [2, 3, 7] bary [[2, 3, 7], [2, 3, 7]]
[[7, 3, 2], [7, 3, 2], [7, 3, 2], [7, 3, 2], [7, 3, 2], [7, 3, 2]]


最后一個列表應該包含每個可能的順序,但它只有輸入值順序,即使它打印每個順序。 那么我在哪里搞砸了return

您的問題是只有一份 ary 副本。 您多次將其附加到 bary 。 所以巴里充滿了同一個列表。 任何時候您對 ary 進行更改。 這將反映在所有這些中,因為它們都是相同的列表。

相反,當您附加到 bary 時,會分配一個 ary 的副本,但作為它自己的新列表,因此在您更改 ary 時不會受到影響

def combinations(ary, p):
    ln = len(ary)
    bary=[]
    for a in range(ln-p):
        if p<ln-2:
            bb = combinations(ary, p+1)
            for be in bb:
                bary.append(be)
        if p>=ln-2:
            bary.append(ary[:]) #Changed this line to take a shallow copy of ary
            print('ary', ary, 'bary', bary)

        ary.append(ary.pop(p))
    return bary

print(combinations([7,3,2], 0))

輸出

ary [7, 3, 2] bary [[7, 3, 2]]
ary [7, 2, 3] bary [[7, 3, 2], [7, 2, 3]]
ary [3, 2, 7] bary [[3, 2, 7]]
ary [3, 7, 2] bary [[3, 2, 7], [3, 7, 2]]
ary [2, 7, 3] bary [[2, 7, 3]]
ary [2, 3, 7] bary [[2, 7, 3], [2, 3, 7]]
[[7, 3, 2], [7, 2, 3], [3, 2, 7], [3, 7, 2], [2, 7, 3], [2, 3, 7]]

暫無
暫無

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

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