It's intriguing to me why default function parameters are mutable in Python. First learned about this when memoising a dynamic programming algorithm and results were different than for non-memoised solution. When I showed this to one of my colleagues at the office, he opened my eyes to the mutable __defaults__
parameter in python. Another colleague made an observation why is this even a feature? Are there use cases when you want this? I'm not a Python engineer, so I'd like to hear from those that are what are your thoughts on this and experiences dealing with this feature.
The aforementioned code:
def can_sum(target, numbers, memo={}):
if target in memo: eturn memo[target]
if target < 0: return False
if target == 0: return True
for number in numbers:
if can_sum(target - number, numbers, memo) == True:
memo[target] = True
return True
memo[target] = False
return False
print(can_sum(7, [2, 4, 6])) # False, actual result False
print(can_sum(7, [1, 5, 2])) # True, actual result False
print(can_sum(112, [1, 2, 3])) # True, actual result True
print(can_sum(17, [2, 4, 6])) # False, actual result True
print(can_sum(1874, [3, 7, 17])) # True, actual result True
Here's a link to a Python sandbox when you can run it and see this in action: https://www.online-python.com/Z2k4u5z8HA