by ryanianian · 4y ago · 0 comments
However this comes up a lot for new engineers during programming interviews. It's very common to see recursive algos use empty lists as default/start-case args:
def traverse(graph, seen_so_far=[]): # Incorrect
....
seen_so_far.append(node)
Subsequent calls to `traverse` will have state accumulated from earlier calls. The right solution is: def traverse(graph, seen_so_far=None):
if not seen_so_far:
seen_so_far = []
.....
This isn't obvious if you're new to Python. This PEP makes this (arguably) clearer with: def traverse(graph, seen_so_far=>[]):It's more concise when you are familiar with it, and it improves introspection and dev tooling when functions use it, but it is not fundamentally clearer.