Lesson 1, Topic 1
In Progress
5.3: Student Activity – Recursion & Lambda Challenge Pack
📦 Practice building recursive functions and using lambda expressions for quick tasks!
🎯 Objective:
By the end of this activity, you'll be able to:
- Define and use recursive functions with base cases
- Create and use lambda functions with
map(),filter(), andsorted() - Solve real problems with short, reusable function logic
🧱 Part 1: Recursion Practice
1️⃣ Sum of Numbers 1 to N
Write a recursive function that returns the sum from 1 to n.
def sum_to_n(n):
if n <= 0:
return 0
else:
return n + sum_to_n(n - 1)
print("Sum to 5:", sum_to_n(5)) # Output: 15
✅ Test with sum_to_n(10), sum_to_n(1), and sum_to_n(0).
2️⃣ Recursive Factorial
def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)
print("5! =", factorial(5)) # Output: 120
✅ Test with factorial(0), factorial(3), and factorial(7).
3️⃣ Fibonacci Sequence
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
print("Fibonacci of 5:", fibonacci(5)) # Output: 5
✅ Try with small numbers only (e.g., fibonacci(6)) — larger values get slow.
⚡ Part 2: Lambda Function Practice
4️⃣ Square a List with map() + lambda
nums = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x * x, nums))
print("Squares:", squares) # [1, 4, 9, 16, 25]
5️⃣ Filter Even Numbers with filter() + lambda
numbers = list(range(20))
evens = list(filter(lambda x: x % 2 == 0, numbers))
print("Evens:", evens) # [0, 2, 4, ..., 18]
6️⃣ Sort Names by Last Letter with sorted() + lambda
names = ["Alice", "Bob", "Charlie", "Zoe"]
sorted_names = sorted(names, key=lambda name: name[-1])
print("Sorted by last letter:", sorted_names)
🧠 Bonus Challenge
7️⃣ Recursive Palindrome Checker
Write a recursive function that checks whether a word is a palindrome (reads the same backward).
def is_palindrome(word):
if len(word) <= 1:
return True
if word[0] != word[-1]:
return False
return is_palindrome(word[1:-1])
print(is_palindrome("racecar")) # True
print(is_palindrome("python")) # False
8️⃣ Lambda to Capitalize All Names
names = ["alice", "bob", "carla"]
capitalized = list(map(lambda s: s.capitalize(), names))
print("Capitalized:", capitalized) # ['Alice', 'Bob', 'Carla']
✅ What to Submit:
- Your complete script with all 8 parts
- Test output from several examples
- (Bonus if attempted) Your palindrome checker or your own lambda + recursion idea
📝 Learning Check
| Task | ✅ |
|---|---|
| Created and tested recursive functions | |
| Used base case + recursive step correctly | |
Used map(), filter(), or sorted() | |
| Wrote at least 2 lambda expressions | |
| Tested code and printed clear results |
