StacksQueues/Python/ArrayStack: Difference between revisions
From charlesreid1
No edit summary |
|||
| Line 128: | Line 128: | ||
=Flags= | |||
[[Category:Stacks]] | [[Category:Stacks]] | ||
| Line 134: | Line 135: | ||
[[Category:Python Stacks]] | [[Category:Python Stacks]] | ||
[[Category:Python Arrays]] | [[Category:Python Arrays]] | ||
{{ | {{DataStructuresFlag}} | ||
Revision as of 06:14, 30 May 2017
Array-Based Stack Implementation.
Class description
Recap: Definition of stack abstract data type (Stack ADT):
A stack is an abstract data type (ADT) such that an instance S supports the following two methods:
- S.push(e): add element e to the top of the stack S
- S.pop: remove and return the top element from the stack S; an error occurs if the stack is empty.
Additionally, accessor methods for convenience:
- S.peek(): get reference to top element without removing it; an error occurs if the stack is empty.
- S.is_empty(): return True if stack S contains no elements
- len(S): implemented via builtin __len__
The ArrayStack class implements the above abstraction using an array-based structure (a list).
Link: https://charlesreid1.com:3000/cs/python/src/master/stacks-queues-deques/stacks/ArrayStack.py
Class test
Taking a look first at our test, we should be able to run the following code after implementing the above methods:
if __name__=="__main__":
a = ArrayStack()
a.push(5)
a.push(15)
a.push(17)
a.push(28)
print("Peeking: {0}".format(a.peek()))
print("Length of stack: {0}".format(len(a)))
a.pop()
a.pop()
a.push(100)
a.push(200)
a.push(300)
a.push(400)
while(not a.is_empty()):
a.pop()
print("Popping... {0}".format(len(a)))
print("Done testing ArrayStack.")
Exceptions and error handling
The specification of the ADT mentions two cases where errors should be thrown - both occurring if the stack is empty.
Create our own Empty exception:
class Empty(Exception):
pass
Class implementation
"""
Stack ADT: ArrayStack
This class implements the following methods:
S.push(e)
S.pop()
S.peek()
S.is_empty()
len(S)
This class utilizes an array-based data structure,
a list, to store its data under the hood.
It only needs to keep track of that list.
This makes it an adapter class for the list,
since it adheres to the Stack ADT but does not change
the implementation of the underlying list type.
"""
class ArrayStack:
"""
Implement the Stack ADT using an array-based data structure (list).
"""
def __init__(self):
self._data = []
def __len__(self):
return len(self._data)
def __str__(self):
return str(self._data)
def is_empty(self):
"""
Check if empty. Don't bother calling our own __len__.
Just do what is sensible.
"""
return (len(self._data)==0)
def push(self,o):
"""
Add an element to the top of the stack
"""
self._data.append(o)
def pop(self):
"""
Pop the next item.
This should handle an empty stack.
"""
if( self.is_empty() ):
raise Empty("Stack is empty")
return self._data.pop()
def peek(self):
"""
Peek at the next item.
This should handle an empty stack.
"""
if( self.is_empty() ):
raise Empty("Stack is empty")
return self._data[-1]
This is an adapter pattern for the list class.
Flags
| Data Structures Part of Computer Science Notes
This is the staging ground for computer science notes as part of the 2017 CS Study Plan.
Classes of data structures: Abstract Data Types Array-based and Link-based memory management: ArrayLists and Linked Lists Algorithmic Analysis of Data Structures: Algorithmic Analysis of Data Structures Advanced data structures: Advanced Data Structures
|
| Arrays Part of Computer Science Notes
Series on Data Structures Python: Arrays/Python · Arrays/Python/Sizeof · Arrays/Python/AppendCost · Arrays/Python/CaesarCipher · Arrays/Python/CompactArrays · Arrays/Python/DynamicArray Java: Arrays/Java · Arrays/Java/CaesarCipher · Arrays/Java/FisherYates · Arrays/Java/PythonList · Arrays/Java/Repeatedly_Remove Categories: Category:Python Arrays
|
| Stacks and Queues Part of Computer Science Notes
Series on Data Structures
Stacks and Queues: Python StacksQueues/Python · StacksQueues/Python/ArrayStack · StacksQueues/Python/ArrayQueue · StacksQueues/Python/ArrayDeque StacksQueues/Python/LinkedStack
Stacks and Queues: Java StacksQueues/Java · StacksQueues/Java/ArrayStack · StacksQueues/Java/ArrayQueue · StacksQueues/Java/ArrayQueueFS · StacksQueues/Java/ArrayDeque StacksQueues/Java/LinkedStack · StacksQueues/Java/LinkedQueue · StacksQueues/Java/LinkedDeque
Applications Postfix_Expressions#Stacks · StacksQueues/Subsets · StacksQueues/Subsets/Java
|
| Priority Queues and Heaps Part of Computer Science Notes
Series on Data Structures
Java: Priority Queues/Java · Priority Queues/ADT · Priority Queues/Sorted · Priority Queues/Unsorted Performance: Priority Queues/Timing and Performance Applications: Maximum Oriented Priority Queue · Priority Queues/Stack
Priority Queues/Heap · Priority Queues/Java · Priority Queues/Comparators
|
| Linked List Part of Computer Science Notes
Series on Data Structures Java: Linked Lists/Java · Linked Lists/Java/Single · Linked Lists/Java/Double · Linked Lists/Java/Circular Performance: Linked Lists/Java/Timing · Linked Lists/Java/Reverse Python: Linked Lists/Python · Linked Lists/Python/Single
|
| Trees Part of Computer Science Notes
Series on Data Structures Abstract data type: Trees/ADT Concrete implementations: Trees/LinkedTree · Trees/ArrayTree · SimpleTree
Tree Traversal Preorder traversal: Trees/Preorder Postorder traversal: Trees/Postorder In-Order traversal: Binary Trees/Inorder Breadth-First Search: BFS Breadth-First Traversal: BFT Depth-First Search: DFS Depth-First Traversal: DFT OOP Principles for Traversal: Tree Traversal/OOP · Tree Traversal/Traversal Method Template Tree operations: Trees/Operations Performance · Trees/Removal
Tree Applications Finding Minimum in Log N Time: Tree/LogN Min Search
Abstract data type: Binary Trees/ADT Concrete implementations: Binary Trees/LinkedBinTree · Binary Trees/ArrayBinTree Binary Trees/Cheat Sheet · Binary Trees/OOP · Binary Trees/Implementation Notes
|
| Search Trees Part of Computer Science Notes
Series on Data Structures
Binary Search Trees · Balanced Search Trees Trees/OOP · Search Trees/OOP · Tree Traversal/OOP · Binary Trees/Inorder
(Note that heaps are also value-sorting trees with minimums at the top. See Template:PriorityQueuesFlag and Priority Queues.)
|
| Maps and Dictionaries Part of Computer Science Notes
Series on Data Structures
Maps/Dictionaries Maps · Maps/ADT · Maps in Java · Maps/OOP · Maps/Operations and Performance Map implementations: Maps/AbstractMap · Maps/UnsortedArrayMap · Maps/SortedArrayMap Dictionary implementations: Dictionaries/LinkedDict · Dictionaries/ArrayDict
Hashes Hash Maps/OOP · Hash Maps/Operations and Performance Hash Maps/Dynamic Resizing · Hash Maps/Collision Handling with Chaining Hash functions: Hash Functions · Hash Functions/Cyclic Permutation Hash map implementations: Hash Maps/AbstractHashMap · Hash Maps/ChainedHashMap
Skip Lists · Java/ConcurrentSkipList · Java implementations: SkipList
Sets Sets · Sets/ADT · Sets in Java · Sets/OOP · Multisets
|