super FunctionAre there any questions before I begin?
Let's look at the answers to Quiz 9.
There is no graded Quiz today, but there will be one next week.
If you have the textbook read Chapter 12, Recursion, sections 12.1 Introduction to Recursion, 12.2 Problem Solving with Recursion and 12.3 Examples of Recursive Algorithms.
I have posted a solution to homework 9 here.
Let's take a look.
I have posted homework 10 here.
This is the last homework assignment.
It is due this Sunday at 11:59 PM.
The final exam will be held on Thursday, December 17th from 3:00 PM - 6:00 PM.
The exam will NOT be given in this room.
It will be given instead in the Pomplun Lab, M03-0730 just down the hall.
If for some reason you are not able to take the Final at the time it will be offered, you MUST send an email to me before the exam so we can make alternative arrangements.
The final will consist of questions taken from the Weekly Graded Quizzes, along with questions asking you to write short segments of Python code.
60% of the points on this exam will consist of questions from all the Graded Quizzes.
You will find links to the answers to all graded quizzes here .
You do not need to study a Graded Quiz question if the topic is not mentioned in either the Midterm or Final review.
The remaining 40% will come from 4 questions that ask you to write some code.
To study for the code questions you should be able to
A good way to study for the code questions is to review the Class Exercises, homework solutions and Class Notes.
You will only be responsible for the material Midterm review, which you will find here and the Final review which is here.
Although the time alloted for the exam is 3 hours, I would expect that most of you would not need that much time.
The final is a closed book exam.
To prevent cheating, certain rules will be enforced during the exam.
Remember, the Midterm and Final determine 50% of your grade.
At the end of each semester we offer you the opportunity to say what you think about this course.
What have I done right?
What have I done wrong?
What can I do better?
You are not asked for you name.
So the submissions are anonymous.
I will not see your responses until after I have submitted grades for this course.
We collect this feedback through Course Evaluations.
I will use what you say to make this course better.
You should have recieved a link to this evaluation in your UMB email.
Today I will discuss recursive functions.
class SUBCLASS_NAME(SUPERCLASS_NAME):
class Movie(Video):
Video.__init__(...)
def __init__(self, name, length, format, director, studio):
Video.__init__(self, name, length, format)
self.__director = director
self.__studio = studio
self.__actors = set()
>>>m1.get_collection_no() 1 >>>m1.get_name() 'Forbidden Planet' >>>m1.get_length() 98 >>>m1.get_format() 'DVD'
def get_director(self):
return self.__director
def get_studio(self):
return self.__studio
def get_actors(self):
return self.__actors
def add_actor(self, name):
self.__actors.add(name)
>>>m1.add_actor("Walter Pidgeon")
>>>m1.add_actor("Anne Francis")
>>>m1.add_actor("Leslie Nielson")
>>>m1.add_actor("Warren Stevens")
>>>m1.get_actors()
['Walter Pidgeon', 'Anne Francis', 'Leslie Nielson', 'Warren Stevens']
def __str__(self):
return str(self.__collection_no) + ": " + self.__name + ", " + \
str(self.__length) + " minutes, " + self.__format + \
" Directed by " + self.__director + ", " + self.__studio
>>>str(m1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/glenn/workspace-mars/it117/resources_it117/code_it117/example_code_it117/11_chapter_example_code/movie.py", line 26, in __str__
' Directed by ' + self.__director + ', ' + self.__studio
AttributeError: 'Movie' object has no attribute '_Movie__collection_no'
super Functionsuper
super returns a pointer to the
the superclass object ...
def __str__(self):
return super().__str__() + " Directed by " + self.__director + ", " + self.__studio
super points to the base class object
def __init__(self, course_name, company, disc_number, instructor, length, format):
Video.__init__(self, "XXX", length, format)
self.__course_name = course_name
self.__company = company
self.__disc_number = disc_number
self.__instructor = instructor
self.__lectures = []
COURSE_NAME: Disc DISC_NO
def get_name(self):
return self.__course_name + ': Disc ' + str(self.__disc_number)
>>>i1.get_name() 'Understanding the Universe: Disc 1'
super().__str__()as we did in Movie
COLLECTION_NO: COURSE_NAME: Disc DISC_NO, INSTRUCTOR
def __str__(self):
return str(super().get_collection_no()) + ': ' +self.get_name() + ', ' + self.__instructor
>>>from instructional import Instructional
>>>i1 = Instructional("Understanding the Universe", "Great Courses", 1, "Alex Filippenko", 180, "DVD")
>>>str(i1)
'1: Understanding the Universe: Disc 1, Alex Filippenko'
def add_lecture(self, lecture):
self.__lectures.append(lecture)
def get_name(self):
return str(super().get_collection_no()) + ": " + self.__course_name + ": Disc " + \
str(self.__disc_number)
def get_course_name(self):
return self.__course_name
def get_company(self):
return self.__company
def get_disc_number(self):
return self.__disc_number
def get_instructor(self):
return self.__instructor
def get_lectures(self):
return self.__lectures
>>>from movie import Movie
>>>m1 = Movie("Forbidden Planet", 98, "DVD", "Fred McLeod Wilcox", "MGM")
>>>from instructional import Instructional
>>>i1 = Instructional("Understanding the Universe", "Great Courses", 1, "Alex Filippenko", 180, "DVD")
>>>videos = []
>>>videos.append(m1)
>>>videos.append(i1)
>>>for video in videos:
... print(video)
... print(video.get_name())
...
2: Forbidden Planet, 98 minutes, DVD Directed by Fred McLeod Wilcox, MGM
Forbidden Planet
1: Understanding the Universe: Disc 1, Instructor Alex Filippenko
Understanding the Universe: Disc 1
$ cat function_calling_function.py
#! /usr/bin/python3
# Demonstrates one function calling another
def function_1(arg):
print("This is function_1 printing it's argument:", arg)
print()
print("function_1 is now calling function_2(' + arg +')")
function_2(arg)
print()
print("This is function_1 signing off")
def function_2(arg):
print()
print("This is function_2 printing it's argument:", arg)
function_1("Hello")
$ ./function_calling_function.py
This is function_1 printing it's argument: Hello
function_1 is now calling function_2("Hello")
This is function_2 printing it's argument: Hello
This is function_1 signing off
>>> def add_one_and_print(num): ... num +=1 ... print(num) ... add_one_and_print(num) ...
>>> add_one_and_print(0) 1 2 3 4 5 ... 994 995 997 998 999
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in add_one_and_print
File "<stdin>", line 4, in add_one_and_print
File "<stdin>", line 4, in add_one_and_print
[Previous line repeated 996 more times]
RecursionError: maximum recursion depth exceeded
def count_down(num):
print(num)
if num > 1:
count_down(num - 1)
10 9 8 7 6 5 4 3 2 1
n!
2! = 1 * 2 = 2
3! = 1 * 2 * 3 = 6 4! = 1 * 2 * 3 * 4 = 24 5! = 1 * 2 * 3 * 4 * 5 = 120
3! = 2! * 3 4! = 3! * 4 5! = 4! * 5
n! = (n-1)! * n
1! = 1
def factorial(num):
if num == 1:
return 1
else:
return factorial(num -1) * num
>>>print("5!:",factorial(5))
5!: 120
1 1
1 1 2 3 5 8 13 21 34 55
F(n) = F(n - 1) + F(n - 2)
F(1) = 1 F(2) = 1
def fibonacci(num):
if num == 1 or num == 2:
return 1
else:
return fibonacci(num - 1) + fibonacci(num - 2)
for loop
for n in range(1, 11):
print(fibonacci(n), end=" ")
1 1 2 3 5 8 13 21 34 55
if length of the string is 0 or 1:
return true
else if the first character and the last character are the same:
return a recursive call to the function using the string stripped of 1st and last character
else:
return false
def palindrome(s):
if len(s) == 0 or len(s) == 1:
return True
elif s[0] == s[-1]:
return palindrome(s[1:-1])
else:
return False
>>> palindrome('rotator')
True
>>> palindrome('roxator')
False
def spaces_remove(phrase):
phrase = phrase.lower()
new_phrase = ''
for ch in phrase:
if ch != ' ':
new_phrase += ch
return new_phrase
>>> phrase = "A man a plan a canal Panama" >>> print(phrase) A man a plan a canal Panama >>> phrase = spaces_remove(phrase) >>> print(phrase) amanaplanacanalpanama >>> print(palindrome(phrase)) True
set count to 0
get a list of all the entries in the current directory
for each entry in list
if entry is a directory
increase count by 1
run the function on entry
and increase count by what it returns
return the count
def dir_count(path):
count = 0
entries = os.listdir(path)
for entry in entries:
entry_path = path + "/" + entry
if os.path.isdir(entry_path):
count += 1
count += dir_count(entry_path)
return count
def binary_search(nums, low, high, value):
if high >= low:
middle_index = (high + low) // 2
# if value is present at the middle_index itself
if nums[middle_index] == value:
return middle_index
# if value is smaller than middle_index value, then it can only
# be present in left of the list
elif nums[middle_index] > value:
return binary_search(nums, low, middle_index - 1, value)
# otherwise the value can only be present in right of the list
else:
return binary_search(nums, middle_index + 1, high, value)
else:
# value is not present in the list
return -1
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 [12, 14, 15, 18, 23, 25, 27, 28, 30, 35, 36, 40, 42, 44, 46, 48, 50]
binary_search(num_list, 0, 16, 25)
middle_index = (16 + 0) // 2 # result is 8
0 1 2 3 4 5 6 7 [12, 14, 15, 18, 23, 25, 27, 28]
binary_search(num_list, 0, 7, 25)
middle_index = (7 + 0) // 2 # result is 3
4 5 6 7 [23, 25, 27, 28]
binary_search(num_list, 4, 7, 25)
middle_index = (7 + 4) // 2 # result is 5
set value to 1
set count to 1
while count is less than number
increment count
set value to count times value
return the value
def factorial(number):
value = 1
count = 1
while count < number:
count += 1
value *= count
return value
>>>print("5!:",factorial(5))
5!: 120
if number is 1
return 1
else:
set first to 0
set second to 1
set count to 1
while count is less than number
increment count by 1
set value to first plus second
set first to second
set second to value
return value
def fibonacci(number):
if number == 1:
return 1
else:
first = 0
second = 1
count = 1
while count < number:
count += 1
value = first + second
first = second
second = value
return value
def fibonacci(num):
if num == 1 or num == 2:
return 1
else:
return fibonacci(num - 1) + fibonacci(num - 2)