Last active
December 18, 2018 16:37
-
-
Save AO8/d57efcfa5537b0c5d5fa4ff19371efa8 to your computer and use it in GitHub Desktop.
Stack practice with Python 3.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Exercise completed as part of Erin Allard's Lynda.com course, | |
| # 'Python Data Structures: Stacks, Queues, and Deques' | |
| class Stack: | |
| """An ADT that stores items in the order in which they were | |
| added. Items are added to and removed from the top of the | |
| stack - LIFO. | |
| """ | |
| def __init__(self): | |
| self.items = [] | |
| def push(self, item): | |
| """Accepts an item as a parameter and appends it to end of list. | |
| It returns nothing. | |
| The run time for this method is O(1), or constant time, because | |
| appending to the end of a list happens in constant time. | |
| """ | |
| return self.items.append(item) | |
| def pop(self): | |
| """This method removes and returns the last item in list, which | |
| is also the top item of the Stack. | |
| The run time for this method is O(1), or constant time, because | |
| popping from the end of a list happens in constant time. | |
| """ | |
| if self.items: | |
| return self.items.pop() | |
| else: | |
| return None | |
| def peek(self): | |
| """This method returns the last item in list, which is also the item | |
| at the top of the Stack. | |
| The run time for this method is O(1), or constant time, because indexing | |
| a list happens in constant time. | |
| """ | |
| if self.items: | |
| return self.items[-1] | |
| else: | |
| return None | |
| def size(self): | |
| """This method returns the length of list that is representing the Stack. | |
| The run time for this method is O(1), or constant time, because finding | |
| the length of a list happens in constant time. | |
| """ | |
| return len(self.items) | |
| def is_empty(self): | |
| """This method simply returns a Boolean value describing whether or not | |
| list is empty. | |
| The run time for this method is O(1), or constant time, because testing for | |
| equality happens in constant time. | |
| """ | |
| return self.items == [] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment