Search⌘ K

Puzzle 19: Explanation

Explore the concept of mutable default arguments in Python functions, why they can lead to unexpected behavior, and learn how to correctly use None to create safer, more reliable function defaults. This lesson helps improve your problem-solving skills with Python puzzles.

We'll cover the following...

Try it yourself

Try executing the code below to verify the results:

Python 3.8
import re
from collections import defaultdict
def word_freq(text, freqs=defaultdict(int)):
"""Calculate word frequency in text. freqs are previous frequencies"""
for word in [w.lower() for w in re.findall(r'\w+', text)]:
freqs[word] += 1
return freqs
freqs1 = word_freq('Duck season. Duck!')
freqs2 = word_freq('Rabbit season. Rabbit!')
print(freqs1)
print(freqs2)

Explanation

One of the solutions to ...