2

I have this depth first tree traversal method:

   def dfs(self, node, visited=[], level=0):
        print( f"len(dfs) visited is {len(visited)} level is {level}.")
        if not node:
            return None

        if node not in visited:
            print(f"{level} {node.value}")
            visited.append(node)
            for child in [node.left, node.right]:
                self.dfs(node=child, visited=visited, level=level+1)

I call this method like so:

>>> from binary_tree import Tree
>>> import random
>>> t = Tree()
>>> for i in range(10):
...     t.insert(random.randint(-10,10))
...
>>> t.dfs(t.root)
len(dfs) visited is 0 level is 0.
0 -1
... expected output ...
len(dfs) visited is 10 level is 4.

But when I repeat the call like so ...

>>> t.dfs(t.root)

I just get this output:

len(dfs) visited is 10 level is 0.

It is as if visited was not set to []. Should visited get reinitialized to []?

martineau
  • 119,623
  • 25
  • 170
  • 301
Red Cricket
  • 9,762
  • 21
  • 81
  • 166
  • One of the major tripping points in Python unfortunately. Never have a mutable object as the default argument unless you're using it for caching or something, and even then it's suboptimal. – Carcigenicate Sep 18 '20 at 15:31
  • 1
    Use `None` as the default, then check for it and assign `[]`. This has the positive side effect that users can explicitly pass `None` as a safe default. – Jonathon Reinhart Sep 18 '20 at 15:35

0 Answers0