Abstract Data Types
- Data Type: information being stored and the operations performed on it
- Abstract: no mention of the implementation
- There are two parts to ADTs: Data Type (what's in them), Operations (what you can do with them)
- When using an OO Programming language, we typically turn an ADT into a class. The ADT essentially defines the classes public methods.
Of course, we typically implement the methods associated with the ADT operations.
ADT examples from CSC108H/A08H
- List
- Data: a sequence of objects, in order
- Operations: append, index into, find, …
- Dictionary
- Data: a collection of key-value pairs
- Operations: insert new pair, look up value based on key, change value associated with key, …
Stack ADT
- Stack data
- a sequence of objects. The objects are removed in the opposite order they are inserted: last in, first out (LIFO).
- Like a stack of plates
- The object at the top is called the top.
- Stack operations
- push(o) Add a new item to the top of the stack.
- pop() Remove and return the top item.
- peek() Return the top item.
- is_empty() test whether the stack is empty
- size() return the number of items on the stack.
- Implementation details not provided! This is what makes it abstract!
- Stack Uses
Object Oriented Programming: A reminder
A class is responsible for maintaining the consistent state of the instance variables.
To do this, we have 'public' methods (functions that operate on instances) that are
supposed to take an instance from one consistent state to another.
A class captures
- IS-A (inheritance)
- HAS-A (instance variables)
- RESPONDS-TO
Example
A Balloon
IS-A: (later)
HAS-A:
amount - the amount of air in the Balloon
capacity - the maximum amount of air the Balloon can hold
popped - True/False (whether this Balloon is popped or not)
RESPONDS-TO:
__init__ - the constructor, when we create a new Balloon
inflate(amount) - add amount to self if self is not popped, possibly popping self
deflate(amount) - remove amount from self if self is not popped
__str__ - obtain a string representation of self
Note: By consistent state in this case, we mean, at all times
0<=self.amount<=self.capacity
Balloon.py is our start at implementing the class Balloon.
Implementing a Stack using classes in Python
Queue ADT
- Queue data
- a sequence of objects. The objects are removed in the order they are inserted: first in, first out (FIFO).
- The objects at the front and back of the queue are called the head and rear or tail.
- Queue operations
- enqueue(o) Put object o on the end of the queue.
- dequeue() Remove and return the object at the front of the queue.
- front() Reveal the front object in the queue, but do not remove it.
- is_empty() test whether the queue is empty
- Queue Uses
- Breadth first search of a tree (later)
- Simulation