Quiz 6 Study Guide
This page contains a list of things you should know before taking Quiz 6. If you have any questions as to the correct answers to any of these questions, please let me know.
Recursion
Lab 09 dealt with recursive functions: those functions which call themselves. You should understand how recursive functions work and be prepared to write simple recursive functions without the aid of the computer. You should know how the stack works with recursive functions; in particular, you should understand that each recursive call generates an additional stack frame and that multiple stack frames for the same function can exist simultaneously.
Exercises
Write each of the following functions both iteratively and recursively. Remember: your recursive function should not include any for
or while
loops.
- A function
summate
which sums the numbers between1
and a parametern
. - A function
factorial
which multiplies the numbers between1
and a parametern
. - A function
revstr
which reverses a string. - A function
dupe_list
which duplicates each element in a list (e.g.duplicate([1,2])
returns a new list[1,1,2,2]
).
Draw a stack diagram of summate(3)
when it reaches its base case.
Classes and Objects
The most recent lectures (and Lab 10) have dealt with classes and objects. You should know how to write a class, how to create an object, and how to call an object’s methods. You should understand the purpose of classes and objects and be prepared to write and debug simple classes without the aid of the computer.
Exercises
Answer the following questions:
- What is the difference between a function and a method?
- What is special about the
__init__
method (also called the constructor)? When is it called? - What is special about the
__str__
method? When is it called? - What is the difference between a class and an object?
- Why is object-oriented programming useful? That is, what is the advantage to using classes and objects rather than just writing programs using the Python we learned before classes and objects?
Write the following classes:
- A
Die
class which represents a six-sided die. It starts with a value of6
and provides two methods:roll
(which picks a new value for the die) andget_value
(which returns the current value of the die). - A
BankAccount
class which takes the owner of the account upon construction and sets the account balance to zero. This class should have adeposit
method (to add money) and acheck_balance
method (to check the balance of the account). - A
Yoyo
class which starts with 14 inches of string and a variabledirection
which is initially"down"
. This class should have amove
method. If the object is moving down, themove
method should subtract an inch of string. If the object has no more string, it begins moving"up"
; a yo-yo moving"up"
adds an inch of string. If the object has all 14 inches of string,move
causes it to start moving"down"
again.