It’s time to add a couple helper methods.
Helper methods simplify the code we’ve written by abstracting and labeling chunks of code into a new function. Here’s an example:
# Adding "!" without a helper saying = "I love helper methods" exclamation = saying + "!" # Adding "!" with a helper def add_exclamation_to_string(str): return str + "!" exclamation2 = add_exclamation_to_string("I love helper methods")
This might seem like a silly example, but think about the benefit of the
First, we want one that checks if our stack has room for more items. We can use this in
push() to guard against pushing items to our stack when it’s full.
Second, it’s helpful to have a method that checks if the stack is empty…
Define a new method
Stack. The method should return
self.limit is greater than
Go back to your
push() method — we need to make sure we’re keeping track of our stack size when we add new items. At the end of your method body, increment
self.size by 1.
Now add an
if clause at the top of
push() that checks if your stack has space (using your newly created helper method).
Finally, let’s define a new method
The method should return
True if the stack’s
size is 0.
Anywhere we’ve written
if self.size > 0: can now be replaced with
if not self.is_empty().