-
Notifications
You must be signed in to change notification settings - Fork 21
/
helpers.py
57 lines (46 loc) · 1.55 KB
/
helpers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import json
import random
from datetime import datetime
from pathlib import Path
from typing import List
from models import Athlete
def get_athletes(directory: str, verbose: bool = False) -> List[Athlete]:
athletes = []
for file_name in Path(directory).glob("*.json"):
with open(file_name) as f:
try:
data = json.load(f)
athletes.append(
Athlete(
name=data["name"],
height=data["height"],
date_of_birth=datetime.strptime(
data["date_of_birth"], "%Y-%m-%d"
),
)
)
except Exception as e:
if verbose:
print(f"Unable to parse {file_name}: {e}")
if verbose:
print(f"Successfully loaded {len(athletes)} athletes.\n")
return athletes
def search_by_name(name: str, athletes: List[Athlete]) -> List[Athlete]:
found = []
for athlete in athletes:
if name.lower() in athlete.name.lower():
found.append(athlete)
return found
def get_random_athlete(search: str, quiet: str, verbose: bool):
athletes = get_athletes("athletes", verbose=verbose)
if search:
athletes = search_by_name(search, athletes)
if not athletes:
return
athlete = random.choice(athletes)
if quiet:
return athlete.name
else:
return (
f"{athlete.name} is {athlete.height_display} and {athlete.age} years old."
)