python
exercises
exercises.pyšpython
"""
05 - Functions: Exercises
Practice function concepts!
"""
print("=" * 60)
print("FUNCTIONS - EXERCISES")
print("=" * 60)
# =============================================================================
# EXERCISE 1: Basic Functions
# =============================================================================
print("\n--- Exercise 1: Basic Functions ---")
# TODO: Write a function that returns the maximum of two numbers
def maximum(a, b):
"""Return the maximum of two numbers."""
pass
# Test:
# print(maximum(5, 3)) # 5
# print(maximum(10, 20)) # 20
# =============================================================================
# EXERCISE 2: Function with Default Parameter
# =============================================================================
print("\n--- Exercise 2: Default Parameters ---")
# TODO: Write a function that greets a person with a customizable greeting
# Default greeting should be "Hello"
def greet(name, greeting="Hello"):
"""Greet a person with a customizable greeting."""
pass
# Test:
# print(greet("Alice")) # Hello, Alice!
# print(greet("Bob", "Hi")) # Hi, Bob!
# =============================================================================
# EXERCISE 3: Multiple Return Values
# =============================================================================
print("\n--- Exercise 3: Multiple Return Values ---")
# TODO: Write a function that returns min, max, sum, and average of a list
def get_statistics(numbers):
"""Return min, max, sum, and average of a list."""
pass
# Test:
# result = get_statistics([1, 2, 3, 4, 5])
# print(result) # (1, 5, 15, 3.0)
# =============================================================================
# EXERCISE 4: *args Function
# =============================================================================
print("\n--- Exercise 4: *args ---")
# TODO: Write a function that calculates the product of any number of arguments
def product(*args):
"""Return the product of all arguments."""
pass
# Test:
# print(product(2, 3, 4)) # 24
# print(product(1, 2, 3, 4, 5)) # 120
# =============================================================================
# EXERCISE 5: **kwargs Function
# =============================================================================
print("\n--- Exercise 5: **kwargs ---")
# TODO: Write a function that creates a formatted person profile string
def create_profile(**kwargs):
"""Create a formatted profile string from keyword arguments."""
pass
# Test:
# print(create_profile(name="Alice", age=25, city="NYC"))
# Output: "name: Alice | age: 25 | city: NYC"
# =============================================================================
# EXERCISE 6: Lambda Functions
# =============================================================================
print("\n--- Exercise 6: Lambda Functions ---")
# TODO: Create lambda functions for:
# a) Square a number
square = None
# b) Check if a number is even
is_even = None
# c) Get the last character of a string
last_char = None
# Test:
# print(square(5)) # 25
# print(is_even(4)) # True
# print(is_even(7)) # False
# print(last_char("Hello")) # 'o'
# =============================================================================
# EXERCISE 7: Sorting with Lambda
# =============================================================================
print("\n--- Exercise 7: Sorting with Lambda ---")
# Given data:
students = [
{"name": "Alice", "grade": 85, "age": 20},
{"name": "Bob", "grade": 92, "age": 22},
{"name": "Charlie", "grade": 78, "age": 19},
{"name": "David", "grade": 92, "age": 21}
]
# TODO: Sort students by:
# a) Grade (ascending)
by_grade = None
# b) Age (descending)
by_age_desc = None
# c) Grade (descending), then by name (ascending) for ties
by_grade_then_name = None
# =============================================================================
# EXERCISE 8: Map and Filter
# =============================================================================
print("\n--- Exercise 8: Map and Filter ---")
# Given:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# TODO: Use map and filter to:
# a) Get squares of all numbers
squares = None
# b) Get only odd numbers
odds = None
# c) Get cubes of even numbers
even_cubes = None
# =============================================================================
# EXERCISE 9: Recursion - Sum of Digits
# =============================================================================
print("\n--- Exercise 9: Recursion ---")
# TODO: Write a recursive function to calculate sum of digits
# Example: 1234 -> 1 + 2 + 3 + 4 = 10
def sum_of_digits(n):
"""Recursively calculate sum of digits."""
pass
# Test:
# print(sum_of_digits(1234)) # 10
# print(sum_of_digits(9999)) # 36
# =============================================================================
# EXERCISE 10: Recursion - Palindrome Check
# =============================================================================
print("\n--- Exercise 10: Palindrome Check ---")
# TODO: Write a recursive function to check if a string is a palindrome
def is_palindrome(s):
"""Recursively check if string is palindrome."""
pass
# Test:
# print(is_palindrome("radar")) # True
# print(is_palindrome("hello")) # False
# print(is_palindrome("a")) # True
# =============================================================================
# EXERCISE 11: Simple Decorator
# =============================================================================
print("\n--- Exercise 11: Simple Decorator ---")
# TODO: Create a decorator that prints "Function started" before
# and "Function ended" after the function executes
def logger(func):
"""Decorator that logs function start and end."""
pass
# Test:
# @logger
# def say_hello(name):
# print(f"Hello, {name}!")
#
# say_hello("Alice")
# Output:
# Function started
# Hello, Alice!
# Function ended
# =============================================================================
# EXERCISE 12: Decorator with Return Value
# =============================================================================
print("\n--- Exercise 12: Decorator with Return ---")
# TODO: Create a decorator that doubles the return value of a function
def double_result(func):
"""Decorator that doubles the function's return value."""
pass
# Test:
# @double_result
# def add(a, b):
# return a + b
#
# print(add(3, 4)) # 14 (7 * 2)
# =============================================================================
# EXERCISE 13: Function Factory
# =============================================================================
print("\n--- Exercise 13: Function Factory ---")
# TODO: Create a function that returns a function to add a specific number
def make_adder(n):
"""Return a function that adds n to its argument."""
pass
# Test:
# add_5 = make_adder(5)
# add_10 = make_adder(10)
# print(add_5(3)) # 8
# print(add_10(3)) # 13
# =============================================================================
# EXERCISE 14: Validator Factory
# =============================================================================
print("\n--- Exercise 14: Validator Factory ---")
# TODO: Create a function that returns a validator for string length
def length_validator(min_len, max_len):
"""Return a function that validates string length."""
pass
# Test:
# username_validator = length_validator(3, 20)
# password_validator = length_validator(8, 50)
#
# print(username_validator("ab")) # False (too short)
# print(username_validator("alice")) # True
# print(password_validator("12345")) # False (too short)
# print(password_validator("securepassword123")) # True
# =============================================================================
# EXERCISE 15: Compose Functions
# =============================================================================
print("\n--- Exercise 15: Compose Functions ---")
# TODO: Write a function that composes two functions f(g(x))
def compose(f, g):
"""Return a new function that computes f(g(x))."""
pass
# Test:
# add_1 = lambda x: x + 1
# multiply_2 = lambda x: x * 2
#
# # First multiply by 2, then add 1
# f = compose(add_1, multiply_2)
# print(f(5)) # 11 (5 * 2 = 10, 10 + 1 = 11)
#
# # First add 1, then multiply by 2
# g = compose(multiply_2, add_1)
# print(g(5)) # 12 (5 + 1 = 6, 6 * 2 = 12)
# =============================================================================
# SOLUTIONS
# =============================================================================
print("\n" + "=" * 60)
print("SOLUTIONS (scroll down after trying!)")
print("=" * 60)
"""
EXERCISE 1:
def maximum(a, b):
return a if a > b else b
EXERCISE 2:
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
EXERCISE 3:
def get_statistics(numbers):
return (min(numbers), max(numbers), sum(numbers), sum(numbers)/len(numbers))
EXERCISE 4:
def product(*args):
result = 1
for num in args:
result *= num
return result
EXERCISE 5:
def create_profile(**kwargs):
return " | ".join(f"{k}: {v}" for k, v in kwargs.items())
EXERCISE 6:
square = lambda x: x ** 2
is_even = lambda x: x % 2 == 0
last_char = lambda s: s[-1] if s else None
EXERCISE 7:
by_grade = sorted(students, key=lambda x: x["grade"])
by_age_desc = sorted(students, key=lambda x: x["age"], reverse=True)
by_grade_then_name = sorted(students, key=lambda x: (-x["grade"], x["name"]))
EXERCISE 8:
squares = list(map(lambda x: x**2, numbers))
odds = list(filter(lambda x: x % 2 != 0, numbers))
even_cubes = list(map(lambda x: x**3, filter(lambda x: x % 2 == 0, numbers)))
EXERCISE 9:
def sum_of_digits(n):
if n < 10:
return n
return n % 10 + sum_of_digits(n // 10)
EXERCISE 10:
def is_palindrome(s):
if len(s) <= 1:
return True
if s[0] != s[-1]:
return False
return is_palindrome(s[1:-1])
EXERCISE 11:
def logger(func):
def wrapper(*args, **kwargs):
print("Function started")
result = func(*args, **kwargs)
print("Function ended")
return result
return wrapper
EXERCISE 12:
def double_result(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs) * 2
return wrapper
EXERCISE 13:
def make_adder(n):
def adder(x):
return x + n
return adder
EXERCISE 14:
def length_validator(min_len, max_len):
def validator(s):
return min_len <= len(s) <= max_len
return validator
EXERCISE 15:
def compose(f, g):
def composed(x):
return f(g(x))
return composed
"""
print("\nš Great job! Move on to 06_modules_packages when ready!")