簡體   English   中英

python在函數中停止遞歸

[英]python stop recursion in a function

我有這個功能,就像樹遍歷一樣,但是要通過字典。 字典中的每個鍵在列表中都有兩個項目,因此結構類似於二叉樹。 我試圖找到一個特定的鍵,同時從給定鍵開始,當我找到鍵時,我想停止我的功能並返回我所在的深度。 我在字典中搜索找到了鍵,但是我的遞歸函數並沒有在return語句處停止。 我的功能:

def count(dict, key, depth):
    if key is not None:
        if key == 42:
            return depth
        return count(map, map[key][0], depth+1)
        return count(map, map[key][1], depth+1)

這里有幾個問題。 其中之一是,你count上自稱遞歸兩次,一次map[key][0]一旦在map[key][1] 但是,如果第一個遞歸調用找到了密鑰,那么大概可以跳過另一個調用,對嗎? 我懷疑您想要更多類似這樣的東西:

if key == 42:
    return depth
found = count(map, map[key][0], depth+1)
if found:
    return found
return count(map, map[key][1], depth+1)

這就帶來了另一個問題: count是否有任何方法可以到達地圖的末尾並得出結論,即找不到鑰匙? 地圖中是否有在map[x][0]map[x][1]沒有有效鍵的條目? 我認為,一旦您解決了這個問題,另一個問題就會變得更加清晰。

您的算法對您要完成的工作不正確。 考慮到永遠不會調用第二個遞歸count 此外,如果目標key 42不在詞典中,該怎么辦。 我想象您想要更接近以下功能的東西:

def find_target_depth(dict, key, target, depth):
  if key is not None:
    if key == target:
      return (True, depth)
    found, found_depth = find_target_depth(dict, dict[key][0], target, depth+1)
    if found:
      return (found,found_depth)
    return find_target_depth(dict, dict[key][1], target, depth+1)
  return (False, 0)

您應該檢查您的最后兩次return縮進return

暫無
暫無

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

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