Puzzle 19: Explanation
Let’s find out how mutable default arguments work in Python.
We'll cover the following...
We'll cover the following...
Try it yourself
Try executing the code below to verify the results:
Press + to interact
Python 3.8
import refrom collections import defaultdictdef 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] += 1return freqsfreqs1 = word_freq('Duck season. Duck!')freqs2 = word_freq('Rabbit season. Rabbit!')print(freqs1)print(freqs2)
Explanation
One of the solutions to ...