-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlibraries_exercises.py
More file actions
68 lines (54 loc) · 2.43 KB
/
Copy pathlibraries_exercises.py
File metadata and controls
68 lines (54 loc) · 2.43 KB
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
58
59
60
61
62
63
64
65
66
67
68
# ==========================================
# Python Learning Lab: 09 Libraries
# ==========================================
import datetime
import os
import random
import re
print("--- Running Standard Libraries Exercises ---")
# ==========================================
# Challenge 1: Datetime Math
# ==========================================
# Write a function that returns a date string exactly 7 days after the input date string.
# Input format: "YYYY-MM-DD"
# Output format: "YYYY-MM-DD"
def add_seven_days(date_str):
# TODO: Parse, add timedelta, and format back to string
d = datetime.datetime.strptime(date_str, "%Y-%m-%d")
d_new = d + datetime.timedelta(days=7)
return d_new.strftime("%Y-%m-%d")
# --- Verification ---
assert add_seven_days("2026-07-10") == "2026-07-17", f"Expected 2026-07-17, got {add_seven_days('2026-07-10')}"
print("✓ Challenge 1 passed!")
# ==========================================
# Challenge 2: Regex Validation
# ==========================================
# Write a function that validates if a string is a valid email address.
# A basic check: ends with @something.com, @something.org, etc.
# Hint: Use re.match() or re.search() with a simple pattern.
def is_valid_email(email):
# TODO: Define regex pattern and return True if matches, False otherwise
pattern = r"^[\w\.-]+@[\w\.-]+\.[a-zA-Z]{2,4}$"
return bool(re.match(pattern, email))
# --- Verification ---
assert is_valid_email("ritshea@github.com") is True, "Should validate ritshea@github.com"
assert is_valid_email("invalid-email") is False, "Should reject invalid-email"
assert is_valid_email("hello@domain") is False, "Should reject hello@domain (missing TLD)"
print("✓ Challenge 2 passed!")
# ==========================================
# Challenge 3: Random Choices
# ==========================================
# Return a random item from the list `words` but set the random seed to 42 first
# to ensure reproducible results.
# Hint: random.seed(42) and random.choice()
def get_reproducible_choice(words):
# TODO: Set seed and return random choice
random.seed(42)
return random.choice(words)
# --- Verification ---
test_words = ["python", "javascript", "rust", "go", "c++"]
choice1 = get_reproducible_choice(test_words)
choice2 = get_reproducible_choice(test_words)
assert choice1 == choice2, f"Choices are not reproducible: {choice1} vs {choice2}"
print("✓ Challenge 3 passed!")
print("\n🎉 All tests passed successfully!")