Last active
January 21, 2026 08:28
-
-
Save kennethleungty/a2294e30a5e733b0b8abd1757cccb4fd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| user_stats.py | |
| Loads user data, validates it, and computes simple statistics. | |
| """ | |
| import csv | |
| from typing import List, Dict | |
| def load_users(path: str) -> List[Dict[str, str]]: | |
| """Load users from a CSV file.""" | |
| with open(path, newline="", encoding="utf-8") as f: | |
| return list(csv.DictReader(f)) | |
| def is_valid(user: Dict[str, str]) -> bool: | |
| """A user is valid if age and score are non-negative numbers.""" | |
| try: | |
| return int(user["age"]) >= 0 and float(user["score"]) >= 0 | |
| except (KeyError, ValueError): | |
| return False | |
| def clean_users(users: List[Dict[str, str]]) -> List[Dict[str, float]]: | |
| """Filter invalid users and normalize types.""" | |
| cleaned = [] | |
| for user in users: | |
| if is_valid(user): | |
| cleaned.append({ | |
| "age": int(user["age"]), | |
| "score": float(user["score"]), | |
| }) | |
| return cleaned | |
| def average_score(users: List[Dict[str, float]]) -> float: | |
| """Compute the average score.""" | |
| if not users: | |
| return 0.0 | |
| return sum(u["score"] for u in users) / len(users) | |
| def main() -> None: | |
| users = load_users("users.csv") | |
| cleaned = clean_users(users) | |
| avg = average_score(cleaned) | |
| print(f"Average score: {avg:.2f}") | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment