簡體   English   中英

為什么在 function 應該完成之后循環重復(看似隨機)?

[英]why is the loop repeating (seemingly randomly) after the function should have completed?

我一直在嘗試編寫一個程序來“從帽子里”畫出成對的名字。 它是為家庭禮物購買的,因此由於住在同一所房子里而有一些“豁免”。 名單上的每個人都會為名單上的其他人購買禮物,並被名單上的其他人購買(下面代碼中的names_in_hat)。

下面的代碼有幾個打印調用來幫助我弄清楚發生了什么。

該代碼似乎運行良好(在豁免列表中出現並重新繪制時拒絕對),直到列表中的所有名稱都出現而沒有遇到任何豁免。 在這一點上,我期待程序剛剛完成(因為 for 循環已經達到其范圍的末端),但我會定期看到更多 - 看似隨機的循環迭代出現,我無法弄清楚為什么......?

在第 47 行添加raise SystemExit(0)之后,我現在已經讓程序按我的意願運行了,這(據我所知)在生成完整的配對名稱列表后立即停止程序。

無論如何,誰能告訴我為什么原始版本(如下,注釋掉了raise SystemExit(0) )繼續超出我預期的最終列表?

謝謝

# script to draw pairs of names 'from a hat' for a 'secret' santa
# certain pairs are not allowed

import random

# names for the draw
names_in_hat = ['Ross', 'Rachel', 'Monica', 'Chandler', 'Joey', 'Phoebe']

# the pairs not allowed
# note this only evaluates pairs EXACTLY as they are shown, i.e. 
# ['Ross', 'Rachel'] isnt same as ['Rachel', 'Ross']
exclusions = [['Ross', 'Rachel'],['Monica', 'Chandler'], ['Joey', 'Phoebe']]

# function to make the draw
def draw(names):

    random.shuffle(names) #shuffle the deck
    #print(names)


    # create empty list to store the drawn pairs
    pairs = []

    #select pairs of names and check if they are in the exclusions list
    for i in range(len(names)):

        if i == len(names)-1:
            D1 = names[i]
            D2 = names[0]
        else:
            D1 = names[i]
            D2 = names[i + 1]

#       THere will be a more elegant way of checkin the selection, regardless of order...
        select_a = [D1, D2]
        select_b = [D2, D1]

        if select_a in exclusions or select_b in exclusions:
            print("**PAIR", select_a, "NOT ALLOWED**")
            print("")
            draw(names) #re-shuffle and re-draw
        else:
            pairs.append(select_a)
            print(i, pairs)

    #print(pairs)
    #raise SystemExit(0) 

draw(names_in_hat)

正如其他人在評論中所建議的那樣,遞歸調用存在一個問題,該循環通常不會在之后立即完成。 在遞歸調用之后立即引入breakreturn ,並將列表作為參數傳遞給 function(為其添加另一個形式參數)(列表通過引用傳遞並且是可變的)。

暫無
暫無

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

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