亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么我的遞歸會導致自引用 dict 值?

為什么我的遞歸會導致自引用 dict 值?

Helenr 2022-07-12 15:47:47
我的目標是編寫一個函數,通過根據收益/成本比比較選項并將它們存儲在嵌套字典列表中,從而在選項之間拆分預算。當具有相同收益/成本比的多個選項可用時,每個選項都應單獨進行(作為下游元素,而下游元素又可能具有多個下游元素)并反映為其上游字典的字典列表。對于可能出現的選項數量沒有限制。def get_all_allocation_proposals(budget, options, upstream_element=dict()):    # accepts:    #   budget to be allocated    #   list of options    # returns:    #   a list of allocation proposals    # filter options for affordable options and sort by cost benefit ratio    options = [x for x in options if x['cost'] <= budget]    options = sorted(options, key=lambda x: (        x['benefit_cost_ratio'], x['benefit']), reverse=True)    if (len(options) > 0):        # select the best options        best_bc_ratio = options[0]['benefit_cost_ratio']        best_options = [            x for x in options if x['benefit_cost_ratio'] == best_bc_ratio]        upstream_element['downstream_elements'] = []        for current_element in best_options:            downstream_options = remove_conflicting_options(                current_element, options)            downstream_budget = budget - current_element['cost']            current_element['donstream_budget'] = downstream_budget            downstream_elements = get_all_allocation_proposals(downstream_budget,                                                               downstream_options,                                                               current_element)            if downstream_elements is not None:                current_element['downstream_elements'] = downstream_elements            upstream_element['downstream_elements'].append(current_element)        return upstream_element    else:        return None在上面的代碼中,當添加元素時,會創建自引用 dict 值。為什么會這樣,我該如何避免呢?我要做的就是將所有下游元素傳遞給第一個調用堆棧。我的遞歸模式是否存在根本缺陷?
查看完整描述

1 回答

?
回首憶惘然

TA貢獻1847條經驗 獲得超11個贊

我認為問題可能是因為您將可變對象傳遞到遞歸調用中。具體來說downstream_options,current_element是 dicts,當你在函數的給定遞歸中修改它們時,你也在上面的級別修改它們,在這種情況下,這似乎讓你試圖在 dict 中為自身分配一個值(或者一些這樣的不可能,我還沒有完全遵循邏輯)。


一個快速的解決方案可能是(我不確定這是否會破壞你的邏輯)在每次遞歸時制作這些字典的副本:


from copy import deepcopy


...


downstream_elements = get_all_allocation_proposals(downstream_budget,

                                                   deepcopy(downstream_options),

                                                   deepcopy(current_element)) 

此外,如評論中所述,您應該避免使用可變的默認參數,即upstream_element=dict(). 如果您實際使用默認值(您的代碼中沒有出現),這可能會產生一些非常令人困惑的行為


查看完整回答
反對 回復 2022-07-12
  • 1 回答
  • 0 關注
  • 116 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號