Puzzle 19 TF (Without IDF)

Python Brain Teasers — by Miki Tebeka (28 / 40)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Round and Round We Go | TOC | A Divided Time 👉

word_freq.py

​1: ​import​ ​re​
​- ​from​ ​collections​ ​import​ defaultdict
​-
​-
​5: ​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
​10:
​-
​- freqs1 = word_freq(​'Duck season. Duck!'​)
​- freqs2 = word_freq(​'Rabbit season. Rabbit!'​)
​- ​print​(freqs1)
​15: ​print​(freqs2)

Guess the Output

IMPORTANT

Try to guess what the output is before moving to the next page.

images/hline.png

This code will print:

​ defaultdict(<class 'int'>, {'duck': 2, 'season': 2, 'rabbit': 2})
​ defaultdict(<class 'int'>, {'duck': 2, 'season': 2, 'rabbit': 2})
images/hline.png

One of the solutions to the Puzzle 11, Click the Button puzzle is using the fact that default arguments to a function are evaluated once when the…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.