super
FunctionLet's look at the answers to Quiz 9.
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 10 here.
Let's take a look.
I have posted homework 11 here.
This is the last homework assignment.
It is due this Sunday at 11:59 PM.
Are there any questions before I begin?
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
connects to the base class objectdef __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'
>>> 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
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
$ 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) ...
1 2 3 4 5 ... 994 995
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 992 more times]
File "<stdin>", line 3, in add_one_and_print
RecursionError: maximum recursion depth exceeded while calling a Python object
996
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 a counter to 0
get a list of all the entries in the current directory
for each entry
if the entry is a directory
increase the count by 1
run the function on this new directory
and increase the 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(num_list, low_index, high_index, value): if num_list_index >= low_index: middle_index = (high_index + low_index) // 2 # if value is present at the middle_index itself if num_list[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 num_list[middle_index] > value: return binary_search(num_list, low_index, middle_index - 1, value) # otherwise the value can only be present in right of the list else: return binary_search(num_list, middle_index + 1, high_index_index, 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 a factorial variable to 1
set a count variable to 1
while count is less than the number whose factorial we are computing
increment count
set factorial to count times the current value of factorial
return the factorial value
def factorial(number): value = 1 count = 1 while count < number: count += 1 value *= count return value
>>> print("5!:",factorial(5)) 5!: 120
if the number is 1
return 1
else:
set the first number variable to 0
set the second number variable to 1
set count to 1
while count is less than the number
increment count by 1
set value to first number plus the second number
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)