My code appears (to me) to return the correct values for all tests, but all tests are failing.
Can anyone point out what painfully obvious thing I’m missing please?
Your code so far
def flatten(container, result=[]):
for i, j in enumerate(container):
if isinstance(j, list):
result = flatten(j, result)
else:
result.append(j)
return result
print(flatten([["L", "M", "N"], ["O", ["P", "Q", ["R", ["S", ["T", "U"]]]]], "V", ["W", ["X", ["Y", ["Z"]]]]]))
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36
Thanks for noticing that but I’m not sure I understand why this is the case. Once the function has terminated with the final return statement, why does the value of result persist to the next function call?
This article discusses this issue. The basic idea is that when you set mutable objects like lists and dictionaries as default values of arguments in function, they can be modified within the function but those modifications will persist across function calls, and there’s a warning of doing this can lead to unexpected behaviour. I don’t know the reason Python is set like this or whether it should be called a bug, but the Rock Scissors Paper project of the legacy Machine Learning in Python course uses this feature to store results across multiple callings of the function.