[CreativeProgramming]Lecture10_Recursion
[CreativeProgramming]Lecture10_Recursion
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
5
Multiplication: Iterative Solution
7
Multiplication: Recursive Solution
8
Multiplication: Recursive Solution
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)
• 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
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
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
21
Exercise #2: Solution
22
Exercise #3: Displaying Recursive Steps of Factorial
23
Exercise #3: Solution
24
Exercise #4: Verifying Palindromes (Assignment #2)
25
Exercise #4: Design Steps
❖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
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