0
def node(tree, List = [], max_depth = 5, counter = 0):
    calls = getattr(node, "calls", 0)  
    print('Calls:', calls)
    question = list(tree.keys())[0]
    yes_answer = tree[question][0]
    no_answer =  tree[question][1]
    if isinstance(yes_answer, dict) and isinstance(no_answer, dict):
        node(yes_answer)
        node(no_answer)
        setattr(node, "calls", calls + 1)
    else:
        setattr(node, "calls", calls + 1)
        if (isinstance(yes_answer, dict) and not isinstance(no_answer, dict)) | (not isinstance(yes_answer, dict) and isinstance(no_answer, dict)):
            counter += 1
            List.append(counter)
            if isinstance(yes_answer, dict) and not isinstance(no_answer, dict):
                node(yes_answer)
            if not isinstance(yes_answer, dict) and isinstance(no_answer, dict):
                node(no_answer)
        else:
            counter +=2
            List.append(counter)
            if calls == max_depth:
                  Summe_Knoten = sum(List)
                  print("Summe Knoten: ", Summe_Knoten)
                  return Summe_Knoten
            
 

Hello, could someone tell me why the Python function always outputs a NonType object? I iterate over a dict and would like the sum of the list at the end. Unfortunately, the function always resets the counter to 0, so I have inserted the list.

  • 1
    When you make the recursive call, it's the same as if you were calling *any other* function: simply calling it computes a value, but then you have to *do something* with it. If you want the current function call to immediately return the value from the recursive call, then that looks the same as immediately returning the value from calling *any other* function: `return the_other_function()`; therefore `return recursive_call()`. There are many duplicate or near-duplicate questions about this; I hope the one I linked is adequate. – Karl Knechtel Sep 06 '21 at 07:46
  • 1
    You only have one condition where Summe_Knoten might be returned. In all other cases it will return None –  Sep 06 '21 at 07:46
  • Separately: please read https://stackoverflow.com/q/1132941. It is a bad idea to use mutable data for recursive algorithms *in general*; that makes them much harder to reason about and to debug. The problem is that changes won't "unwind" as you return from the recursive calls. Using a list as a default parameter makes things worse, because that default value won't be reset *between top-level calls* to the function, either. – Karl Knechtel Sep 06 '21 at 07:48

0 Answers0