I don't understand why a recursive function inside a for loop doesn't exit the function at the base case.
I am reading grokking algorithms and trying to implement an example for understanding.
box = [
[["key"], []],
[[], []],
[[], []]
]
def find_key(box):
for item in box:
print(item)
if item == "key":
print("found")
return
elif type(item) == type([]):
print("looking in next box")
find_key(item)
find_key(box)
I would expect that once the key is found, the function is exited, but it continues to look through the rest of the list.
This might also be my lack of understanding of what return does especially related to recursive calls. I can get my expected behavior using
import sys
def find_key(box):
for item in box:
if item == "key":
print("found")
sys.exit()
elif type(item) == type([]):
print("looking in next box")
find_key(item)
find_key(box)