Skip to content
Snippets Groups Projects
Commit 1c07dc13 authored by LOUIS TYRRELL OLIPHANT's avatar LOUIS TYRRELL OLIPHANT
Browse files

lec 22 recursion

parent 5a19bbf7
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id: tags:
## Warmup
%% Cell type:code id: tags:
``` python
# Warmup 0: What is the difference between these two pieces of code?
```
%% Cell type:code id: tags:
``` python
groceries = ["apples", "bananas", "coconuts", "dragonfruit"]
groceries_dicts = []
for grocery in groceries:
grocery_dict = {}
grocery_dict['name'] = grocery
grocery_dict['size'] = len(grocery)
groceries_dicts.append(grocery_dict)
groceries_dicts
```
%% Cell type:code id: tags:
``` python
groceries = ["apples", "bananas", "coconuts", "dragonfruit"]
groceries_dicts = []
grocery_dict = {}
for grocery in groceries:
grocery_dict['name'] = grocery
grocery_dict['size'] = len(grocery)
groceries_dicts.append(grocery_dict)
groceries_dicts
```
%% Cell type:code id: tags:
``` python
# Warmup 1a: Use 'in' to determine if something is in my_list
my_list = ["meet", "me", "after", 84]
```
%% Cell type:code id: tags:
``` python
# Warmup 1b: What about this list?
my_list = [11, "meet", ["me", "them", "us"], [84,19, 22], "school", 2.54]
```
%% Cell type:code id: tags:
``` python
# Warmup 2a: Write a function to find a thing in a list that may have lists in it
my_list = [11, "meet", ["me", "them", "us"], [84,19, 22], "school", 2.54]
def search_list_depth2(target, some_list):
pass
print(search_list_depth2("school", my_list)) # in list
# print(search_list_depth2(22, my_list)) # in nested list
# print(search_list_depth2("house", my_list)) # not anywhere
```
%% Cell type:code id: tags:
``` python
# Warmup 2b: Will our function work on this list? Guess:
list_3_deep = [22, [33, 44, [55, 66], 77 ], 88]
# let's try it with our previous function
print(search_list_depth2(22, list_3_deep)) # in list
print(search_list_depth2(99, list_3_deep)) # not in list
# Write other tests to be sure that it works
```
%% Cell type:code id: tags:
``` python
# Warmup 2c: What about ANY depth list?
# That is the goal of today's lecture
list_3_deep = [22, [33, 44, [55, 66], 77 ], 88]
def search_list_depth_any(target, some_list):
pass
search_list_depth_any(55, list_3_deep)
```
%% Cell type:markdown id: tags:
# Recursion
## Readings
- [Downey Ch 5 ("Recursion" through "Infinite Recursion")](https://greenteapress.com/thinkpython2/html/thinkpython2006.html), [Ch 6 ("More Recursion" through end)](https://greenteapress.com/thinkpython2/html/thinkpython2007.html)
## Objectives
After today's Lecture you will be able to:
- Define recursion and be able to identify
- the base case
- the recursive case
- infinite recursion
- Explain why the following can be recursively defined
- lists
- dictionaries
- Trace a recursive function
- involving numeric computation
- involving nested data structures
%% Cell type:markdown id: tags:
## What is Recursion?
Recursion is defined as the process of defining something in terms of itself.
This is commonly done when writting a function. **A recursive function is one that calls itself.** This can be very dangerous because you can get infinite recursion:
```python
def func():
func()
```
What happens if you were to call this function?
%% Cell type:code id: tags:
``` python
def func():
func()
func()
```
%% Cell type:markdown id: tags:
![image.png](attachment:image.png)
%% Cell type:markdown id: tags:
### Define recursion and be able to identify
- the base case
- the recursive case
- infinite recursion
%% Cell type:code id: tags:
``` python
# In math, you can define the factorial of a number in terms of the number before it.
# Q: What is the value of 84! (84 factorial)
# A:
# What are we still missing?
# A:
```
%% Cell type:markdown id: tags:
### A recursive algorithm must have 2 parts:
- the base case....which stops the recursion
- the recursive case...which defines the same process in a smaller way
#### If there is no base case what happens in the above example?
- recursion never ends......infinite recursion
- infinite recursion can also happen if the recursive case does not move towards the base
%% Cell type:markdown id: tags:
### Writing Definitions Recursively
%% Cell type:code id: tags:
``` python
# Define the sequence 1, 3, 5, 7, 9, 11... recursively
# Base Case:
# Recursive Case:
```
%% Cell type:code id: tags:
``` python
# Define whether a positive number is odd recursively
# Base Case:
# Recursive Case:
```
%% Cell type:markdown id: tags:
### Writing Recursive Code
%% Cell type:code id: tags:
``` python
def factorial(n):
pass
print(factorial(0))
# print(factorial(3))
# print(factorial(6))
```
%% Cell type:markdown id: tags:
### Write and try `is_odd` in [PythonTutor](https://pythontutor.com/render.html#code=def%20is_odd%28n%29%3A%0A%20%20%20%20if%20n%20%3D%3D%201%3A%0A%20%20%20%20%20%20%20%20return%20True%0A%20%20%20%20elif%20n%20%3D%3D%200%3A%0A%20%20%20%20%20%20%20%20return%20False%0A%20%20%20%20else%3A%0A%20%20%20%20%20%20%20%20if%20n%20%3C%200%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20return%20is_odd%28n%20%2B%202%29%0A%20%20%20%20%20%20%20%20else%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20return%20is_odd%28n%20-%202%29%0Aprint%28is_odd%28-3%29%29&cumulative=false&curInstr=0&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false)
%% Cell type:code id: tags:
``` python
def is_odd(n):
pass
is_odd(7)
```
%% Cell type:markdown id: tags:
### Can we write them iteratively instead?
%% Cell type:code id: tags:
``` python
def factorial_itr(n):
pass
print(factorial_itr(0))
# print(factorial_itr(3))
# print(factorial_itr(6))
```
%% Cell type:markdown id: tags:
### Other Recursive Problems
%% Cell type:code id: tags:
``` python
# The Collatz Conjecture problem
# Conjecture: Any positive integer n, put through the below equation
# will always converge to 1.
#
# https://en.wikipedia.org/wiki/Collatz_conjecture
# https://www.youtube.com/watch?v=5mFpVDpKX70
# >$1 million award for solving. And likely an honorary doctorate.
# Run this in Python Tutor on your own
def collatz(n):
print(n)
if n == 1:
return 1 # base case
elif n % 2 == 0:
return collatz(n//2)
else:
return collatz (3*n+1)
collatz(13) # try other numbers
```
%% Cell type:markdown id: tags:
### Trace a recursive function involving nested data structures
%% Cell type:code id: tags:
``` python
fav_stuff = [ "road bike",
["PB&J", "brownies", "spaghetti", "apples"] ,
("Brooks Ghost 13", "hoodie", "gloves"),
"macbook air",
[ "Johndee.com", "https://www.weather.gov/mkx/"],
["A", "K", ("S", "D", "K")]
]
print ("road bike" in fav_stuff)
print ("brownies" in fav_stuff) # Why is this False?
```
%% Cell type:code id: tags:
``` python
# Write a recursive function to search *ANY* list of lists/tuples for a given word
# Modify your code from Warmup 2.C
def search_list_recursive(target, some_list):
pass
print(search_list_recursive("apples", fav_stuff))
# print(search_list_recursive("D", fav_stuff))
# print(search_list_recursive("road bike", fav_stuff))
# print(search_list_recursive("pizza", fav_stuff))
```
%% Cell type:code id: tags:
``` python
# Write a function that prints nested lists with indenting
#
def print_with_indenting(directory, indent_level):
for thing in directory:
if type(thing) == list or type(thing) == tuple:
print("\t" * indent_level + str(type(thing)))
print_with_indenting(thing, indent_level + 1)
else:
print("\t" * indent_level + str(thing))
print_with_indenting(fav_stuff, 0)
```
%% Cell type:markdown id: tags:
### Dictionaries can have a recursive structure
As can...
- lists
- dictionaries
- JSON objects
%% Cell type:code id: tags:
``` python
ancestry = {
"name": "Evan",
"age": 28,
"born": "Sheboygan",
"parent": {
"name": "Dean",
"age": 53,
"born": "Milwaukee",
"parent": {
"name": "Mike",
"age": 74,
"born": "Racine",
"parent": {
"name": "Bill",
"age": 96,
"born": "La Crosse"
}
}
}
}
```
%% Cell type:code id: tags:
``` python
# let's try to search through a deep dictionary.
def find_place_of_birth(target_name, ancestry_history):
if ancestry_history['name'] == target_name: # base case
return ancestry_history['born']
else:
if 'parent' in ancestry_history:
return ???
return "Unknown!"
find_place_of_birth("Evan", ancestry)
```
%% Cell type:code id: tags:
``` python
# Extra practice...can you predict the outcome?
# run this on your own in Python Tutor
def mystery(a, b):
# precondition: a > 0 and b > 0
if a < 0 or b < 0:
return None
if b == 1:
return a;
return a * mystery( a, b - 1 )
# make a function call here
mystery(7, 5)
```
This diff is collapsed.
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment