Creative Programming
Spring 2025
CUL1122 Lecture #10
Recursion
Today
❖Recursion
❖Iteration vs. Recursion
▪ Multiplication
▪ Factorial of a Number
❖Palindrome
❖Exercises
3
Recursion
❖Recursion is the process of solving a problem in terms of a simpler
version of itself
❖Consider a problem of finding your way home:
▪ 1. If you have arrived home, stop moving
▪ 2. Otherwise, take one step towards home
▪ 3. Repeat the process of finding your way home for
a shorter distance
❖Here is a general solution to finding your way home in three steps:
▪ First, determine if the goal has been achieved
▪ Secondly, perform a simple action that simplifies the problem
▪ Finally, repeat the entire process for the simplified problem
4
Recursion
❖In terms of algorithm,
▪ Recursion defines a problem using a divide-and-conquer approach
▪ It breaks down a problem into simpler ones, making them easier to solve
▪ Recursion solves a problem by breaking it down into simpler versions of itself
❖In terms of programming,
▪ Recursion is the technique of a function calling itself
▪ Infinite recursion occurs when the function never stops calling itself
▪ Every recursive function should include a halting condition, where the function
stops calling itself
5
Multiplication: Iterative Solution
❖An iterative process for multiplication involves performing integer
multiplication through repeated addition
▪ For example, a*b = a + a + a +… + a + a
Adding a b times
❖Here is the definition of the iterative version of the 'mult_iter' function:
def mult_iter(a, b):
result = 0
while b > 0: # Continue as long as b is greater than 0
Repetition
result += a # Add a to the current sum
b -= 1 # Decrease b by one
return result
6
Multiplication: Iterative Solution
▪ e.g., a = 3, b = 5
def mult_iter(a, b):
result = 0 Repetition
while b > 0: b=5 → result=3, b=4 3*5 = 3 + 3 + 3 + 3 + 3
result += a b=4 → result=6, b=3
b -= 1 Repeating 5 times
b=3 → result=9, b=2
return result b=2 → result=12, b=1
b=1 → result=15, b=0
sol=mult_iter(3, 5) ▪ Output
print(sol)
7
Multiplication: Recursive Solution
❖A recursive function typically consists of two fundamental components:
▪ Recursive step:
➢This step computes the result by making one or more recursive calls to the same
function
➢Each call reduces the size of the inputs, moving closer to a base case
▪ Base case:
➢The base case is a condition that allows the function to compute the result immediately, without
further recursion
➢It provides the terminating condition for the recursion
8
Multiplication: Recursive Solution
❖Here is the definition of the recursive version of the 'mult_recur'
function:
def mult_recur(a, b): a*b = a + a + a +… + a + a
if b == 1: # When b is equal to 1 Repeating b times
Base case
return a = a + a + a +… + a + a
else : Recursive Repeating b-1 times
return a + mult_recur(a, b-1) step
= a + a * (b-1)
Recursive reduction
9
Multiplication: Recursive Solution
▪ e.g., a = 3, b = 5
def mult_recur(a, b):
if b == 1:
Base case
return a
else : Recursive 3*5 = 3 + 3 * (5-1)
return a + mult_recur(a, b-1) step Recursive reduction
sol=mult_recur(3, 5) ▪ Output
print(sol)
mult_recur(3, 5) mult_recur(3, 4) mult_recur(3, 3) mult_recur(3, 2) mult_recur(3, 1)
sol=mult_recur(3,5) if5==1 : if4==1 : if3==1 : if2==1 : if1==1 :
return 3 return 3 return 3 return 3 return3 Basecase
print(sol) 15 else: else: else: else:
else:
return3+mult_recur(3, 4) return3+mult_recur(3, 3) return3+mult_recur(3, 2) return3+mult_recur(3, 1) return 3+mult_recur(3, 0)
3+12 3+9 3+6 3+3
10
Factorial of a Number
▪ A recursive process for factorial of a given number
• n! = n * (n-1) * (n-2) * (n-3) * … * 1
• n! = 1 # if n = 1
n * (n-1)! # Otherwise
• Base case
➢n=1 → if n == 1:
return 1
• Recursive step
➢ n * (n-1)! → else:
return n*factorial(n-1)
Recursive reduction
11
Factorial of a Number
▪ Iteration vs. recursion
# Factorial-Iterative Solution # Factorial-Recursive Solution
def fact_iter(n): def fact_recur(n):
result = 1 if n == 1:
for a in range(1, n+1): return 1
result *= a else:
return result return n * fact_recur(n-1)
• Using recursion results in shorter code, but it often takes more time
• On the other hand, iteration usually requires more code, but it tends to be faster
12
Recursion on Nonnumeric Data
❖A palindrome is a word, phrase, or
sentence that reads the same forward
and backward.
❖For example:
▪ “Able was I, ere I saw Elba.” – attributed to
Napoleon.
▪ “Are we not drawn onward, we few, drawn
onward to new era?” – attributed to Anne
Michaels.
13
Use Recursion to Check a Palindrome
❖We start by converting the input string to lowercase and removing all
non-alphanumeric characters.
▪ Base case
➢If the length of the string is 0 or 1, we can consider it a palindrome.
➢If we reach this base case and the string is a palindrome, we return True.
▪ Recursive step
➢If the first and last letters of the string are equal, we call the function again, passing in a
copy of the string minus the first and last characters as the argument.
➢The recursion will continue as long as we have matching letters or until we reach our
base case.
14
Use Recursion to Check a Palindrome
❖Example
15
Palindrome Checker
def isPalindrome(s): ※ String indexing
def toChars(s):
P y t h o n
s = s.lower() # lower() returns a string where all letters are in lowercase.
Positive 0 1 2 3 4 5
ans = ‘’ Indexing
for c in s: # Remove all non-alphanumeric characters. Negative -6 -5 -4 -3 -2 -1
if c in ‘abcdefghijklmnopqrstuvwxyz’: Indexing
ans = ans + c
return ans ※ String slicing: [1:-1]
P y t h o n
def isPal(s): Base case Positive 0 1 2 3 4 5
Indexing
if len(s) <= 1: # When the length of the string is less than or equal to 1
Negative -6 -5 -4 -3 -2 -1
return True # It is a palindrome, so return True.
Indexing
else : Recursive
return s[0] == s[-1] and isPal(s[1:-1]) step
return isPal(toChars(s))
16
Lab 10
Today
❖1) Multiplying Two Numbers
❖2) Calculating Factorial
❖3) Displaying Recursive Steps of Factorial
❖4) Verifying Palindromes (Assignment #2)
18
Exercise #1: Multiplying Two Numbers
❖Create a Python script that multiplies two integers, num1 and num2
▪ Define functions for multiplication in the program: mult_iter and mult_recur
▪ These functions should utilize a loop and recursion, respectively
19
Exercise #1: Solution
20
Exercise #2: Calculating Factorial
❖Following a similar format to Exercise #1, develop a Python script to
calculate the factorial of a given number
▪ Within the program, define functions: fact_iter and fact_recur
▪ Utilize a loop and recursion for these functions, respectively
21
Exercise #2: Solution
22
Exercise #3: Displaying Recursive Steps of Factorial
❖Rewrite the fact_recur function to display its recursive steps as
demonstrated below
23
Exercise #3: Solution
24
Exercise #4: Verifying Palindromes (Assignment #2)
❖Create a script that assesses whether provided strings are palindromes
using both iterative and recursive approaches.
25
Exercise #4: Design Steps
❖1) Input Handling:
▪ Prompt the user to enter a string.
➢This will be the input that needs to be verified as a palindrome.
❖2) Preprocessing:
▪ Create a function called prepare_input that transforms the input string:
➢Convert to Lowercase: This ensures that the comparison is case-insensitive.
➢Filter Characters: Iterate through the string and collect only alphanumeric characters,
ignoring spaces and punctuation. This is done using a loop that checks each character
with the isalpha() and isnumeric() methods.
▪ For example, ‘A Santa at NASA.’ becomes ‘a santa at nasa.’ and then transforms
to ‘asantatnasa’.
26
Exercise #4: Design Steps
❖3) Iterative Palindrome Check:
▪ Define a function called check_palindrome_iterative:
➢Reverse the String: Create a reversed version of the processed string.
➢Compare Characters: Use a loop to compare each character of the original and reversed
strings. If a mismatch is found, return False. If all characters match, return True.
Index 0 1 2 3 4 5 6 7 8 9 10 11
Original String a s a n t a a t n a s a
Reversed String a s a n t a a t n a s a
27
Exercise #4: Design Steps
❖4) Recursive Palindrome Check:
▪ Define a function called check_palindrome_recursive:
➢Base Case: If the string length is 0 or 1, return True, as such strings are inherently
palindromes.
➢Recursive Step: Compare the first and last characters of the string. If they are equal,
recursively check the substring that excludes these two characters. If they are not equal,
return False.
❖5) Execution and Output:
▪ After preprocessing the string:
➢Call the iterative check function and store the result. Print whether the string is a
palindrome based on the iterative method.
➢Call the recursive check function and store the result. Print whether the string is a
palindrome based on the recursive method.
28
수고하셨습니다!
29