-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfinal_assessment.py
More file actions
170 lines (139 loc) · 5.71 KB
/
Copy pathfinal_assessment.py
File metadata and controls
170 lines (139 loc) · 5.71 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
# ==========================================
# Python Learning Lab: Final Assessment
# ==========================================
# Solve the five core challenges below to complete the course!
# Run: `python final_assessment.py` to check your work.
import os
import json
print("--- Running Final Assessment ---")
# ==========================================
# Challenge 1: Memoized Fibonacci
# ==========================================
# Write a recursive function `fibonacci(n)` that returns the n-th Fibonacci number.
# Implement a basic dictionary memoization (`memo = {}`) to optimize execution speed.
# Fibonacci Sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34...
memo = {}
def fibonacci(n):
# TODO: Implement memoized fibonacci
if n in memo:
return memo[n]
if n == 0:
return 0
if n == 1:
return 1
memo[n] = fibonacci(n - 1) + fibonacci(n - 2)
return memo[n]
# --- Verification ---
assert fibonacci(0) == 0, "Fib(0) should be 0"
assert fibonacci(1) == 1, "Fib(1) should be 1"
assert fibonacci(10) == 55, "Fib(10) should be 55"
assert fibonacci(50) == 12586269025, "Memoization is required or n=50 will hang!"
print("✓ Challenge 1 passed!")
# ==========================================
# Challenge 2: Anagram Detector
# ==========================================
# Write a function `is_anagram(str1, str2)` that returns True if two strings are
# anagrams of each other (case-insensitive, ignoring spaces).
# An anagram is a word formed by rearranging the letters of another (e.g. "Listen", "Silent").
def is_anagram(str1, str2):
# TODO: Clean strings and determine if they are anagrams
clean1 = sorted(str1.lower().replace(" ", ""))
clean2 = sorted(str2.lower().replace(" ", ""))
return clean1 == clean2
# --- Verification ---
assert is_anagram("Listen", "Silent") is True, "Listen and Silent are anagrams"
assert is_anagram("Astronomer", "Moon starer") is True, "Spaces and case should be ignored"
assert is_anagram("hello", "bello") is False, "Not anagrams"
print("✓ Challenge 2 passed!")
# ==========================================
# Challenge 3: Word Count Analytics
# ==========================================
# Write a function `word_frequencies(paragraph)` that:
# 1. Splits text by space and strips punctuation marks (comma, period, exclamation).
# 2. Converts words to lowercase.
# 3. Returns a dictionary containing word-to-count mapping.
def word_frequencies(paragraph):
# TODO: Perform text processing and count word occurrences
import string
words = paragraph.lower().split()
counts = {}
for w in words:
cleaned = w.strip(string.punctuation)
if cleaned:
counts[cleaned] = counts.get(cleaned, 0) + 1
return counts
# --- Verification ---
text = "Python is great. Learning Python is fun! Programming is also great."
counts = word_frequencies(text)
assert counts["python"] == 2, f"Expected 2 pythons, got {counts.get('python')}"
assert counts["is"] == 3, f"Expected 3 'is', got {counts.get('is')}"
assert counts["fun"] == 1, f"Expected 1 'fun', got {counts.get('fun')}"
print("✓ Challenge 3 passed!")
# ==========================================
# Challenge 4: Custom Abstract Class Structure
# ==========================================
# 1. Define an abstract class `Shape` with an abstract method `area()`.
# 2. Create `Circle` subclass initializing with `radius`.
# 3. Create `Rectangle` subclass initializing with `width` and `height`.
# 4. Use `3.14159` as value for pi.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
# TODO: Set radius
self.radius = radius
def area(self):
# TODO: Return area of circle
return 3.14159 * (self.radius ** 2)
class Rectangle(Shape):
def __init__(self, width, height):
# TODO: Set width and height
self.width = width
self.height = height
def area(self):
# TODO: Return area of rectangle
return float(self.width * self.height)
# --- Verification ---
circle = Circle(5)
rectangle = Rectangle(4, 6)
assert abs(circle.area() - 78.53975) < 1e-4, f"Circle area incorrect: {circle.area()}"
assert rectangle.area() == 24.0, f"Rectangle area incorrect: {rectangle.area()}"
print("✓ Challenge 4 passed!")
# ==========================================
# Challenge 5: Log Parser Pipeline
# ==========================================
# Complete `parse_and_export_logs(log_data, output_filepath)`:
# 1. Parse lines of text where format is: "[LEVEL] MESSAGE" (e.g. "[ERROR] Connection failed")
# 2. Filter for logs containing '[ERROR]'.
# 3. Write those error messages as a list of strings into a JSON file at `output_filepath`.
def parse_and_export_logs(log_lines, output_filepath):
# TODO: Parse lines, filter errors, and write to JSON
errors = []
for line in log_lines:
if line.startswith("[ERROR]"):
msg = line.replace("[ERROR] ", "", 1)
errors.append(msg)
with open(output_filepath, "w") as f:
json.dump(errors, f)
# --- Verification ---
logs = [
"[INFO] System started",
"[ERROR] Database unreachable",
"[WARN] High memory usage detected",
"[ERROR] Disk sector corrupt"
]
out_path = "errors.json"
parse_and_export_logs(logs, out_path)
assert os.path.exists(out_path), "JSON output file was not generated"
with open(out_path, "r") as f:
errors = json.load(f)
assert len(errors) == 2, f"Expected 2 error logs, got {len(errors)}"
assert "Database unreachable" in errors, "Could not find expected error message"
# Cleanup
if os.path.exists(out_path):
os.remove(out_path)
print("✓ Challenge 5 passed!")
print("\n🎉 Congratulations! You have passed the Python Final Assessment!")