# Python Typing Practice Comprehensive Code
# Type each line carefully, pay attention to indentation, colons, brackets, etc.
import math
import random
from collections import Counter
# Part 1: Variables and Basic Operations
name = "Alice"
age = 25
height = 1.68
is_student = True
print(f"Name: {name}, Age: {age}, Height: {height}, Student: {is_student}")
# Part 2: Lists and Loops
numbers = [random.randint(1, 100) for _ in range(10)]
total = 0
for num in numbers:
total += num
average = total / len(numbers)
print(f"Numbers: {numbers}")
print(f"Total: {total}, Average: {average:.2f}")
# Part 3: Dictionaries and Conditionals
person = {
"name": "Bob",
"age": 30,
"city": "New York",
"skills": ["Python", "Java", "SQL"]
}
if person["age"] >= 18:
print(f"{person['name']} is an adult.")
else:
print(f"{person['name']} is a minor.")
# Part 4: Function Definition and Calls
def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)
def is_prime(num):
if num < 2:
return False
for i in range(2, int(math.sqrt(num)) + 1):
if num % i == 0:
return False
return True
print(f"Factorial of 5: {factorial(5)}")
print(f"Is 17 prime? {is_prime(17)}")
# Part 5: Exception Handling
def divide_safely(a, b):
try:
result = a / b
except ZeroDivisionError:
print("Error: Cannot divide by zero")
return None
except TypeError:
print("Error: Invalid operand types")
return None
else:
print(f"Division successful: {a} / {b} = {result}")
return result
finally:
print("Division operation completed.")
divide_safely(10, 2)
divide_safely(10, 0)
# Part 6: Classes and Inheritance
class Shape:
def __init__(self, color="black"):
self.color = color
def area(self):
raise NotImplementedError("Subclass must implement area method")
class Circle(Shape):
def __init__(self, radius, color="red"):
super().__init__(color)
self.radius = radius
def area(self):
return math.pi * self.radius ** 2
class Rectangle(Shape):
def __init__(self, width, height, color="blue"):
super().__init__(color)
self.width = width
self.height = height
def area(self):
return self.width * self.height
shapes = [Circle(3, "green"), Rectangle(4, 5)]
for shape in shapes:
print(f"{shape.__class__.__name__} area: {shape.area():.2f}, color: {shape.color}")
# Part 7: List Comprehensions and Generator Expressions
squares = [x**2 for x in range(1, 11)]
even_squares = [x**2 for x in range(1, 21) if x % 2 == 0]
cubes_gen = (x**3 for x in range(5))
print(f"Squares: {squares}")
print(f"Even squares: {even_squares}")
print(f"Cubes: {list(cubes_gen)}")
# Part 8: String Manipulation and Formatting
text = "The quick brown fox jumps over the lazy dog"
words = text.split()
word_freq = Counter(words)
most_common_word = word_freq.most_common(1)[0][0]
reversed_text = " ".join(reversed(words))
print(f"Original: {text}")
print(f"Words count: {len(words)}")
print(f"Most common word: '{most_common_word}'")
print(f"Reversed: {reversed_text}")
# Part 9: File Operations (simulated write and read)
file_content = """Line 1: Hello World
Line 2: This is a test file.
Line 3: Python makes it easy.
Line 4: End of file."""
with open("test_output.txt", "w") as f:
f.write(file_content)
with open("test_output.txt", "r") as f:
for line_number, line in enumerate(f, 1):
print(f"{line_number}: {line.strip()}")
# Part 10: Decorators
def debug(func):
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__} with args={args}, kwargs={kwargs}")
result = func(*args, **kwargs)
print(f"{func.__name__} returned {result}")
return result
return wrapper
@debug
def add(a, b):
return a + b
add(3, 5)
# Part 11: Lambda and Higher-order Functions
multiply = lambda x, y: x * y
numbers_list = [1, 2, 3, 4, 5]
doubled = list(map(lambda x: x * 2, numbers_list))
filtered = list(filter(lambda x: x > 2, numbers_list))
from functools import reduce
product = reduce(lambda a, b: a * b, numbers_list)
print(f"Doubled: {doubled}")
print(f"Filtered (>2): {filtered}")
print(f"Product: {product}")
# Part 12: Sets and Enumerate
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
union = set1 | set2
intersection = set1 & set2
difference = set1 - set2
symmetric_difference = set1 ^ set2
print(f"Union: {union}")
print(f"Intersection: {intersection}")
print(f"Difference: {difference}")
print(f"Symmetric difference: {symmetric_difference}")
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# Part 13: Recursion and Algorithm Example
def binary_search(arr, target, low, high):
if low > high:
return -1
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
return binary_search(arr, target, mid + 1, high)
else:
return binary_search(arr, target, low, mid - 1)
sorted_arr = [1, 3, 5, 7, 9, 11, 13]
target = 7
index = binary_search(sorted_arr, target, 0, len(sorted_arr) - 1)
print(f"Binary search: Index of {target} is {index}")
# Part 14: Simple Multithreading Example (syntax demonstration only)
import threading
import time
def worker(name, delay):
print(f"Worker {name} started")
time.sleep(delay)
print(f"Worker {name} finished after {delay}s")
threads = []
for i in range(3):
t = threading.Thread(target=worker, args=(i, i+1))
threads.append(t)
t.start()
for t in threads:
t.join()
print("All workers done")
# Part 15: Regular Expression Matching
import re
pattern = r"\b[A-Za-z]{4}\b" # matches exactly 4-letter words
matches = re.findall(pattern, text)
print(f"Four-letter words found: {matches}")
# Clean up temporary file
import os
if os.path.exists("test_output.txt"):
os.remove("test_output.txt")
print("Temporary file removed.")
print("\n--- End of Practice Code ---")