lania Skrevet mandag kl 08:23 Del Skrevet mandag kl 08:23 (endret) Python Programming Fundamentals Course Examination Course Introduction This examination assesses your understanding of fundamental Python programming concepts covered in the "Python Programming Fundamentals" course. Throughout this course, you have explored: Basic syntax and data structures Control flow (conditionals and loops) Functions and modular programming Object-oriented programming concepts Error handling File operations Basic algorithms and problem-solving techniques This exam will test both your theoretical knowledge and practical coding abilities. For coding questions, you will need to either write complete solutions or fill in missing code sections to complete the given programs. Part I: Python Fundamentals (20 points) 1. Variable Types (5 points) Identify the data type that would be returned by each of the following expressions: a) 5 // 2 b) 7.0 / 2 c) "Hello" + "World" d) [1, 2, 3] + [4, 5] e) {"name": "John", "age": 30}.keys() 2. List Operations (5 points) Complete the missing code to perform the following operations: numbers = [10, 20, 30, 40, 50] # a) Add the value 60 to the end of the list # YOUR CODE HERE # b) Insert the value 15 at index 1 # YOUR CODE HERE # c) Remove the value 30 from the list # YOUR CODE HERE # d) Reverse the list # YOUR CODE HERE # e) Create a new list containing only values greater than 25 result = # YOUR CODE HERE 3. String Manipulation (5 points) Complete the function to convert a string to title case (first letter of each word capitalized) without using the .title() method: def custom_title_case(text): """ Convert a string to title case (capitalize first letter of each word) Args: text (str): Input string to be converted Returns: str: Converted string in title case """ # YOUR CODE HERE # Example usage: # custom_title_case("hello world") should return "Hello World" 4. Dictionary Operations (5 points) Complete the function that takes a list of students with their scores and returns a dictionary with the student names as keys and their grades as values, based on the following grading scale: 90-100: 'A' 80-89: 'B' 70-79: 'C' 60-69: 'D' Below 60: 'F' def assign_grades(students_scores): """ Assign letter grades to students based on their scores Args: students_scores (list): List of tuples containing (student_name, score) Returns: dict: Dictionary with student names as keys and letter grades as values """ # YOUR CODE HERE # Example: # assign_grades([("Alice", 92), ("Bob", 85), ("Charlie", 70), ("David", 55)]) # Should return: {"Alice": "A", "Bob": "B", "Charlie": "C", "David": "F"} Part II: Control Flow (20 points) 5. Conditional Statements (5 points) Complete the following function that determines if a year is a leap year: def is_leap_year(year): """ Determine if a given year is a leap year A leap year is divisible by 4, but not by 100 unless it's also divisible by 400 Args: year (int): Year to check Returns: bool: True if leap year, False otherwise """ # YOUR CODE HERE # Examples: # 2000 and 2020 are leap years # 1900 and 2023 are not leap years 6. Loops (5 points) Complete the function to generate a pattern of asterisks as shown in the example: def generate_pattern(rows): """ Generate a pattern of asterisks Args: rows (int): Number of rows in the pattern Returns: str: The pattern as a string """ # YOUR CODE HERE # Example: # generate_pattern(5) should return: # * # ** # *** # **** # ***** 7. Nested Loops (5 points) Complete the function to create a multiplication table of size n × n: def multiplication_table(n): """ Generate a multiplication table of size n × n Args: n (int): Size of the multiplication table Returns: list: 2D list representing the multiplication table """ # YOUR CODE HERE # Example: # multiplication_table(3) should return: # [[1, 2, 3], [2, 4, 6], [3, 6, 9]] 8. List Comprehensions (5 points) Convert each of the following loop-based code snippets to equivalent list comprehensions: # a) Create a list of squares of numbers from 1 to 10 squares = [] for i in range(1, 11): squares.append(i ** 2) # Convert to list comprehension: squares = # YOUR CODE HERE # b) Filter out odd numbers from a list numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] even_numbers = [] for num in numbers: if num % 2 == 0: even_numbers.append(num) # Convert to list comprehension: even_numbers = # YOUR CODE HERE # c) Create a list of tuples with numbers and their squares numbers = [1, 2, 3, 4, 5] result = [] for num in numbers: result.append((num, num ** 2)) # Convert to list comprehension: result = # YOUR CODE HERE Part III: Functions and Modularity (20 points) 9. Function Parameters (5 points) Complete the function that calculates the total price after applying a discount: def calculate_price(items, discount=0, tax_rate=0.08): """ Calculate the total price after discount and tax Args: items (list): List of item prices discount (float, optional): Discount rate as a decimal (default: 0) tax_rate (float, optional): Tax rate as a decimal (default: 0.08) Returns: float: Final price after discount and tax """ # YOUR CODE HERE # Example: # calculate_price([10, 20, 30], 0.1) should calculate: # Subtotal: 60, After discount: 54, After tax: 58.32 10. Recursive Functions (5 points) Complete the recursive function to calculate the Fibonacci sequence: def fibonacci(n): """ Calculate the nth Fibonacci number recursively Args: n (int): Position in the Fibonacci sequence (0-indexed) Returns: int: The nth Fibonacci number """ # YOUR CODE HERE # Examples: # fibonacci(0) = 0 # fibonacci(1) = 1 # fibonacci(6) = 8 11. Lambda Functions (5 points) Replace the following functions with equivalent lambda expressions: # a) Function to calculate the square of a number def square(x): return x ** 2 # Replace with lambda: square_lambda = # YOUR CODE HERE # b) Function to check if a number is even def is_even(x): return x % 2 == 0 # Replace with lambda: is_even_lambda = # YOUR CODE HERE # c) Function to convert temperature from Celsius to Fahrenheit def celsius_to_fahrenheit(celsius): return (celsius * 9/5) + 32 # Replace with lambda: celsius_to_fahrenheit_lambda = # YOUR CODE HERE 12. Higher-Order Functions (5 points) Complete the following code using map, filter, and reduce (from functools): from functools import reduce numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # a) Use map to create a list of squares of all numbers squares = # YOUR CODE HERE # b) Use filter to get only the even numbers evens = # YOUR CODE HERE # c) Use reduce to calculate the product of all numbers product = # YOUR CODE HERE # d) Chain operations: get the sum of squares of even numbers result = # YOUR CODE HERE Part IV: Object-Oriented Programming (20 points) 13. Class Definition (5 points) Define a class Rectangle with the following specifications: Attributes: length and width Methods: calculate_area(), calculate_perimeter(), is_square() class Rectangle: """ A class representing a rectangle """ # YOUR CODE HERE # Example usage: # rect = Rectangle(5, 10) # rect.calculate_area() should return 50 # rect.calculate_perimeter() should return 30 # rect.is_square() should return False 14. Inheritance (5 points) Create a class Student that inherits from the following Person class: class Person: def __init__(self, name, age): self.name = name self.age = age def introduce(self): return f"My name is {self.name} and I am {self.age} years old." class Student(Person): """ A class representing a student, inheriting from Person Additional attributes: student_id, courses (list of enrolled courses) Additional methods: enroll(course), display_courses() """ # YOUR CODE HERE # Example usage: # student = Student("Alice", 20, "S12345") # student.introduce() should include student ID # student.enroll("Math 101") # student.display_courses() should show enrolled courses 15. Static and Class Methods (5 points) Complete the BankAccount class with instance, static, and class methods: class BankAccount: interest_rate = 0.02 # Class variable total_accounts = 0 # Class variable to track the number of accounts def __init__(self, account_number, balance=0): self.account_number = account_number self.balance = balance # Increment the total number of accounts BankAccount.total_accounts += 1 def deposit(self, amount): """Instance method to deposit money""" # YOUR CODE HERE def withdraw(self, amount): """Instance method to withdraw money""" # YOUR CODE HERE @classmethod def set_interest_rate(cls, rate): """Class method to set the interest rate for all accounts""" # YOUR CODE HERE @staticmethod def validate_account_number(account_number): """Static method to validate if an account number is valid Valid account numbers must be 10 digits """ # YOUR CODE HERE 16. Magic Methods (5 points) Implement the following magic methods in the Vector class to perform vector operations: class Vector: def __init__(self, x, y, z): self.x = x self.y = y self.z = z def __str__(self): """String representation of the vector""" # YOUR CODE HERE def __add__(self, other): """Add two vectors""" # YOUR CODE HERE def __sub__(self, other): """Subtract other vector from this vector""" # YOUR CODE HERE def __eq__(self, other): """Check if two vectors are equal""" # YOUR CODE HERE def __mul__(self, scalar): """Multiply vector by a scalar""" # YOUR CODE HERE Part V: Error Handling and File Operations (20 points) 17. Exception Handling (5 points) Complete the function to safely divide two numbers, handling potential errors: def safe_divide(a, b): """ Safely divide a by b, handling potential errors Args: a (float): Numerator b (float): Denominator Returns: float: Result of division, or None if error occurs """ # YOUR CODE HERE # Examples: # safe_divide(10, 2) should return 5.0 # safe_divide(10, 0) should handle the ZeroDivisionError # safe_divide("10", 2) should handle the TypeError 18. Custom Exceptions (5 points) Create a custom exception and use it in a function that validates user input: # Define custom exception # YOUR CODE HERE def validate_username(username): """ Validate a username according to the following rules: - Must be between 5 and 20 characters - Must contain only alphanumeric characters and underscores - Must start with a letter Args: username (str): Username to validate Returns: bool: True if valid Raises: InvalidUsernameError: If username is invalid, with appropriate message """ # YOUR CODE HERE 19. File Reading (5 points) Complete the function to read a CSV file and calculate statistics: def analyze_csv(filename): """ Read a CSV file with numeric data and calculate basic statistics The CSV file has headers in the first row and numeric data in all other rows Args: filename (str): Name of the CSV file Returns: dict: Dictionary with column names as keys and dictionaries of statistics as values Each statistics dictionary should have: min, max, mean, sum """ # YOUR CODE HERE # Example CSV format: # Name,Age,Height,Weight # John,28,175,82 # Alice,24,163,55 # ... 20. File Writing (5 points) Complete the function to log message with timestamps to a file: import datetime def log_message(filename, message, mode='a'): """ Log a message with a timestamp to a file Args: filename (str): Name of the log file message (str): Message to log mode (str, optional): File opening mode (default: 'a' for append) """ # YOUR CODE HERE # Example: # log_message("application.log", "User logged in") # Should append a line like: "2023-04-28 14:30:45 - User logged in" Part VI: Problem Solving (20 points) 21. Algorithm Implementation (10 points) Implement a function to find the largest continuous sum in a list: def max_subarray_sum(arr): """ Find the largest sum of any contiguous subarray Args: arr (list): List of integers (positive and negative) Returns: int: Largest sum of any contiguous subarray """ # YOUR CODE HERE # Examples: # max_subarray_sum([-2, 1, -3, 4, -1, 2, 1, -5, 4]) should return 6 (sum of [4, -1, 2, 1]) # max_subarray_sum([-1, -2, -3]) should return -1 (the single largest element) 22. Data Processing (10 points) Complete the function to process a list of transactions and generate a summary: def process_transactions(transactions): """ Process a list of financial transactions and generate a summary Each transaction is a dictionary with keys: - 'date': string in format 'YYYY-MM-DD' - 'amount': float (positive for income, negative for expense) - 'category': string Args: transactions (list): List of transaction dictionaries Returns: dict: Summary with keys: - 'total_income': total positive amounts - 'total_expense': total negative amounts (as positive number) - 'net': income minus expenses - 'categories': dictionary with categories as keys and their total amounts as values - 'monthly': dictionary with months ('YYYY-MM') as keys and their net amounts as values """ # YOUR CODE HERE # Example: # transactions = [ # {'date': '2023-01-15', 'amount': 1000, 'category': 'Salary'}, # {'date': '2023-01-20', 'amount': -50, 'category': 'Food'}, # {'date': '2023-02-10', 'amount': -200, 'category': 'Rent'}, # {'date': '2023-02-15', 'amount': 1000, 'category': 'Salary'}, # ] # should return a dictionary with the appropriate summary Extra Credit: Advanced Python Concepts (10 points) 23. Generators (5 points) Implement a generator function that yields prime numbers: def prime_generator(limit): """ Generator that yields prime numbers up to a given limit Args: limit (int): Upper bound (inclusive) Yields: int: Next prime number """ # YOUR CODE HERE # Example: # list(prime_generator(20)) should return [2, 3, 5, 7, 11, 13, 17, 19] 24. Decorators (5 points) Create a decorator that measures and logs the execution time of functions: import time import functools def timing_decorator(func): """ Decorator that measures and prints the execution time of a function Args: func: The function to decorate Returns: The wrapped function with timing functionality """ # YOUR CODE HERE # Example use: @timing_decorator def slow_function(n): time.sleep(n) return n * n # When calling slow_function(2), it should print the execution time (approximately 2 seconds) End of Examination Total Points: 100 (+10 Extra Credit) Endret mandag kl 08:24 av lania Lenke til kommentar
backtoback Skrevet mandag kl 09:54 Del Skrevet mandag kl 09:54 (endret) @lania, flott eksamensoppgave Her er oppgaven som en Jupyter Notebook: python-exam.ipynb Endret mandag kl 20:38 av backtoback Lenke til kommentar
Anbefalte innlegg
Opprett en konto eller logg inn for å kommentere
Du må være et medlem for å kunne skrive en kommentar
Opprett konto
Det er enkelt å melde seg inn for å starte en ny konto!
Start en kontoLogg inn
Har du allerede en konto? Logg inn her.
Logg inn nå