Cookie Jar
Source: Sesame Street
Suppose that you’d like to implement a cookie jar in which to store cookies. In a file called jar.py
, implement a class
called Jar
with these methods:
__init__
should initialize a cookie jar with the givencapacity
, which represents the maximum number of cookies that can fit in the cookie jar. Ifcapacity
is not a non-negativeint
, though,__init__
should instead raise aValueError
(viaraise ValueError
).__str__
should return astr
with \(n\)🍪
, where \(n\) is the number of cookies in the cookie jar. For instance, if there are 3 cookies in the cookie jar, thenstr
should return"🍪🍪🍪"
deposit
should addn
cookies to the cookie jar. If adding that many would exceed the cookie jar’s capacity, though,deposit
should instead raise aValueError
.withdraw
should removen
cookies from the cookie jar. Nom nom nom. If there aren’t that many cookies in the cookie jar, though,withdraw
should instead raise aValueError
.capacity
should return the cookie jar’s capacity.size
should return the number of cookies actually in the cookie jar.
Structure your class
per the below. You may not alter these methods’ parameters, but you may add your own methods.
class Jar:
def __init__(self, capacity=12):
...
def __str__(self):
...
def deposit(self, n):
...
def withdraw(self, n):
...
@property
def capacity(self):
...
@property
def size(self):
...
Demo
You’re welcome, but not required, to implement a main
function in which to test your class, so this is all we can demo!
Source: Sesame Street
Before You Begin
- Log into cs50.dev using your GitHub account.
- Click inside the terminal window and execute
cd
. - Execute
wget https://cdn.cs50.net/2022/fall/labs/6/jar.zip
followed by Enter in order to download a zip calledjar.zip
in your codespace. Take care not to overlook the space betweenwget
and the following URL, or any other character for that matter! - Now execute
unzip jar.zip
to create a folder calledjar
. - You no longer need the ZIP file, so you can execute
rm jar.zip
and respond with “y” followed by Enter at the prompt.
How to Test
Here’s how to test your code manually:
- Define a
main
function in yourjar.py
file, wherein you create a new instance ofJar
withjar = Jar()
. Test thisjar
has the capacity it should by callingprint(str(jar.capacity))
. Be sure your program callsmain
at the bottom of the file, as viamain()
. - Test that your
__str__
function works as intended by callingprint(str(jar))
. - Try calling
jar.deposit(2)
to deposit two cookies. Callingprint(str(jar))
should now show you the same number of cookies you’ve deposited. - Try calling
jar.withdraw(1)
to withdraw one cookie. Callingprint(str(jar))
should now show you one fewer cookie than you had before. - Try experimenting with depositing and withdrawing various amounts of cookies. Are you unable to withdraw past the jar’s size? Are you unable to deposit past the jar’s capacity?
No check50
for this one!
How to Submit
No need to submit! This is a practice problem.