### Lecture9

```CIT 590
Recursion
Recursion
• A function calling itself
• Factorial
def factorial(n):
if n == 0: return 1
return n * factorial(n-1)
Recursion
• Does solving a smaller problem help me solve a bigger
one.
• Lists are naturally recursive
• A list of n elements contains in it a list of n-1 elements
• In many languages, lists are defined recursively in this manner
• A list of 1 element is a single element
• A list of n elements consists of the start element and a list of n-
1elements
• Python makes extraction of portions of the list super easy
List recursion examples
• Sum of elements of a list
• Finding max of a list
• Replicate - I want to initialize a list with repeats of a
certain number
All in recursionOnLists.py
Divide and Conquer
( a method of solving a problem)
• Divide the problem into smaller problem with (usually)
similar structure
• Solve the smaller problems
• Now aggregate/rollup the smaller solutions to get the
solution to the original problem
Classic divide and conquer = mergesort
• Sort a list
• If I divide the list into 2 halves and sort each half does that
help?
• 2 sorted lists can be merged
Mergesort
Merge
• Making a larger sorted array from 2 smaller sorted ones
• Exploit the fact that you know the relative ordering within
the arrays
def merge(a1, a2):
a3 = []
len1 = len(a1)
len2 = len(a2)
i=j=0
while i < len1 and j < len2:
if a1[i] < a2[j]:
a3.append(a1[i])
i += 1
else:
a3.append(a2[j])
j += 1
# we would either have gone through
# all of a1 or all of a2 by this time
# just tack on the remaining stuff at the end
if i < len1:
a3.extend(a1[i:])
if j < len2:
a3.extend(a2[j:])
return a3
Palindrome finding
• palindrome.py
A string is a palindrome if and only if
Its first character and its last character are the same
Everything between the first and the last character is a
palindrome
Obviously, a single character string is a palindrome.
```