Skip to content

Instantly share code, notes, and snippets.

@chetgray
Last active February 4, 2022 18:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chetgray/d0301185ac51b4e39c61c787610d57fa to your computer and use it in GitHub Desktop.
Save chetgray/d0301185ac51b4e39c61c787610d57fa to your computer and use it in GitHub Desktop.
LibraryThing programming quiz

[...]

Input is a string—a paragraph of text. One of the paragraphs above would be fine.

Output is a report listing how many words there are with X letters, like:

10 words with 1 letter
20 words with 2 letters
7 words with 3 letters
15 words with 4 letters, etc.
from collections import defaultdict
import re
def print_word_counts(text: str="") -> None:
words = re.split("[\W_]+", text)
length_counts = defaultdict(int)
for word in words:
length_counts[len(word)] += 1
for length in sorted(length_counts.keys()):
print(
f"{length_counts[length]} word{'s' if length_counts[length] != 1 else ''}"
f"with {length} letter{'s' if length != 1 else ''}"
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment