45 lines
1.1 KiB
Python
45 lines
1.1 KiB
Python
"""Provides functions to report statistics on books"""
|
|||
|
|
|
||
|
|
from typing import TypedDict
|
||
|
|
|
||
|
|
|
||
|
|
class CharacterCount(TypedDict):
|
||
|
|
"""Represents number of times a character is found in a book"""
|
||
|
|
|
||
|
|
char: str
|
||
|
|
num: int
|
||
|
|
|
||
|
|
|
||
|
|
def count_words_in_book(book_content: str) -> int:
|
||
|
|
"""Returns the count of words in the book"""
|
||
|
|
|
||
|
|
return len(book_content.split())
|
||
|
|
|
||
|
|
|
||
|
|
def count_characters_in_book(book_content: str) -> dict[str, int]:
|
||
|
|
"""Returns a dictionary of the number of times a character appears in the book"""
|
||
|
|
|
||
|
|
result = {}
|
||
|
|
|
||
|
|
for character in book_content:
|
||
|
|
normalized_character = character.lower()
|
||
|
|
|
||
|
|
if normalized_character in result:
|
||
|
|
result[normalized_character] += 1
|
||
|
|
continue
|
||
|
|
|
||
|
|
result[normalized_character] = 1
|
||
|
|
|
||
|
|
return result
|
||
|
|
|
||
|
|
def sort_character_counts(counts: dict[str, int]) -> list[CharacterCount]:
|
||
|
|
"""Returns a list of character counts in descending order"""
|
||
|
|
result: list[CharacterCount] = []
|
||
|
|
|
||
|
|
for entry in counts:
|
||
|
|
result.append({ "char": entry, "num": counts[entry] })
|
||
|
|
|
||
|
|
result.sort(reverse=True, key=lambda x: x["num"])
|
||
|
|
|
||
|
|
return result
|