Skip to content

Instantly share code, notes, and snippets.

@mahenzon
Created December 7, 2024 18:07
Show Gist options
  • Save mahenzon/46bab4703934cdfd2918052621212bca to your computer and use it in GitHub Desktop.
Save mahenzon/46bab4703934cdfd2918052621212bca to your computer and use it in GitHub Desktop.
Python defaultdict examples
# SOME_SENTENCE = input("Enter a sentence: ")
from collections import defaultdict
from collections.abc import Iterable
SOME_SENTENCE = (
"The cat sat on the mat, "
"and the cat played with the mat "
"while the cat watched the sun."
)
SOME_NAMES = [
"Alice",
"Bob",
"Bob",
"Bob",
"Sam",
"Sam",
"Charlie",
"Jessica",
"Jessica",
"Diana",
"Fiona",
"George",
"Nick",
"Jo",
"Jo",
"Isaac",
"Julia",
]
SOME_PLACES_WITH_PEOPLE = {
"The Red Square": {"Ivan", "Olga", "Peter", "Sergey"},
"The Big Ben": {"Kate", "Ivan", "Charles", "Olga"},
"The Golden Bridge": {"John", "Ivan", "Kate", "Peter"},
}
# SOME_PLACES_WITH_PEOPLE = {
# "Ivan": [
# "The Red Square",
# "The Big Ben",
# "The Golden Bridge",
# ],
# "Kate": [
# "The Big Ben",
# "The Golden Bridge",
# ],
# }
def demo_count_words_in_sentence(sentence: str) -> None:
words = (
# original
sentence
# lower case
.lower()
# remove dots
.replace(".", "")
# remove commas
.replace(",", "")
# split by space
.split()
)
print(words)
words_counts: defaultdict[str, int] = defaultdict(int)
# print(words_counts)
# print("foobar count:", words_counts["foobar"])
# print(words_counts)
# print("foobar count:", words_counts["foobar"])
# words_counts["foobar"] = 42
# print("foobar count:", words_counts["foobar"])
# print(words_counts)
for word in words:
words_counts[word] += 1
# if word not in words_counts:
# words_counts[word] = 0
# words_counts[word] += 1
# if word in words_counts:
# words_counts[word] += 1
# else:
# words_counts[word] = 1
print(words_counts)
def demo_group_names_by_length(all_names: Iterable[str]) -> None:
# names_by_length: defaultdict[int, list[str]] = defaultdict(list)
names_by_length: defaultdict[int, set[str]] = defaultdict(set)
for name in all_names:
names_by_length[len(name)].add(name)
for count, names in sorted(names_by_length.items(), reverse=True):
print("===", count)
print(names)
def demo_may_seen_each_other(
places_with_people: dict[str, set[str]],
) -> None:
# {"John": {"Venue A": {"A", "B", "C"}}}
type PlacesWithPeople = defaultdict[str, defaultdict[str, set[str]]]
places_where_seen_each_other: PlacesWithPeople = (
# defaultdict(lambda: defaultdict(lambda: {"Airport"}))
defaultdict(lambda: defaultdict(set))
)
for venue, people in places_with_people.items():
for person1 in people:
for person2 in people:
if person1 != person2:
places_where_seen_each_other[person1][venue].add(person2)
print(places_where_seen_each_other)
seen = (
"Olga"
in places_where_seen_each_other["Ivan"]["The Red Square"]
# places_where_seen_each_other["Ivan"]["The Red Square"].__contains__("Olga")
)
print("Ivan seen Olga at The Red Square:", seen)
seen = "Kate" in places_where_seen_each_other["Charles"]["The Big Ben"]
print("Charles seen Kate at The Big Ben:", seen)
seen = "Kate" in places_where_seen_each_other["Charles"]["The Golden Bridge"]
print("Charles seen Kate at The Golden Bridge:", seen)
def main() -> None:
demo_count_words_in_sentence(SOME_SENTENCE)
demo_group_names_by_length(SOME_NAMES)
demo_may_seen_each_other(SOME_PLACES_WITH_PEOPLE)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment