Student Activity

Student Activity Guide:

1) Defining and Calling Functions

  • Write a function that takes two numbers and returns their sum.

  • Create a function that checks if a number is prime.

Example Code:

def add_numbers(a, b):
    return a + b

print(add_numbers(5, 10))  # Output: 15

# Function to check if a number is prime
def is_prime(n):
    if n < 2:
        return False
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False
    return True

print(is_prime(11))  # Output: True

2) Lambda Functions and Anonymous Functions

  • Write a lambda function that squares a number.

  • Use lambda functions with map() to square a list of numbers.

Example Code:

square = lambda x: x**2
print(square(4))  # Output: 16

# Using lambda with map
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x**2, numbers))
print(squared_numbers)  # Output: [1, 4, 9, 16, 25]

3) Using Map, Filter, and Reduce

  • Use map() to double each number in a list.

  • Use filter() to get only even numbers from a list.

  • Use reduce() to compute the product of a list.

Example Code:

from functools import reduce

# Using map to double numbers
doubled_numbers = list(map(lambda x: x * 2, numbers))
print(doubled_numbers)  # Output: [2, 4, 6, 8, 10]

# Using filter to get even numbers
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)  # Output: [2, 4]

# Using reduce to find the product of numbers
product = reduce(lambda x, y: x * y, numbers)
print(product)  # Output: 120

4) Recursion and Higher-Order Functions

  • Write a recursive function to compute the factorial of a number.

  • Use a higher-order function that takes another function as input.

Example Code:

# Recursive factorial function
def factorial(n):
    if n == 0:
        return 1
    return n * factorial(n - 1)

print(factorial(5))  # Output: 120

# Higher-order function
def apply_function(func, value):
    return func(value)

result = apply_function(lambda x: x**3, 3)
print(result)  # Output: 27

Student Exercises:

  1. Write a function that returns the Fibonacci series up to n using recursion.

  2. Use map() to convert a list of strings to uppercase.

  3. Implement a higher-order function that takes a function and applies it to a given list.

  4. Experiment with filter() to extract words longer than 4 characters from a list of words.

Last updated