Computer Science 112 Fundamentals of Programming II Overview of Collections
The Need for Collections Some programs need a container to manage several data objects You’ve used lists, tuples, and dictionaries in Python There are other types of collections as well
What Is a Collection? A collection is a container for zero or more data objects A collection tracks its own size and resizing is automatic A collection comes with built-in operations for access, insertions, removals, etc. Details of the underlying data structures and operations are hidden in the implementation, so we ignore them
Built in Python Collections String Tuple List Set Dictionary
Basic Categories of Collections Linear Hierarchical Graph Unordered
Linear Collections List Stack Queue Priority Queue D1D2D Elements are ordered by position Each element except the first has a unique predecessor Each element except the last has a unique successor
Linear Collections List Stack Queue Priority Queue D1D2D Lists allow accesses, replacements, insertions, and removals at any position
Linear Collections List Stack Queue Priority Queue D1D2D Stacks allow accesses, insertions and removals at one end only
Linear Collections List Stack Queue Priority Queue D1D2D Queues allow insertions at one end and removals and accesses at the other end
Linear Collections List Stack Queue Priority Queue D1D2D Priority queues sort elements by priority, but elements with equal priority are added and removed in queue-like order
Hierarchical Collections Binary tree General tree Binary search tree Heap D1 D2 D3 Each element except the root has a unique predecessor Each can have zero or more successors
Graph Collections Undirected graph Directed graph D4 D3 D5 D1D2 Each element can have zero or more predecessors Each can have zero or more successors
Unordered Collections Bag Set Dictionary D4 D3 D5 D1D2
Sorted Collections Sorted Set Sorted Dictionary D4 D3 D5 D1D2 The elements are not ordered by position, but they are ordered by content
Aspects of a Collection Formal properties (what it is and what you can do with it – as expressed in its interface) Implementations – array-based, link-based, etc. Performance characteristics – space/time tradeoffs of different implementations
Basic Types of Operations Create a collection: list(), list(aCollection) Obtain the string representation: str(aCollection) Obtain the number of items currently in the collection: len(aCollection)
Basic Types of Operations Test an item for membership: item in aCollection Iterate through the items: for item in aCollection:... Concatenate two collections (of the same type): aCollection1 + aCollection2 Test for equality: aCollection == anObject
Basic Types of Operations Make the collection empty: aCollection.clear() Add an item: aCollection.add(item) Remove an item: aCollection.remove(item)
For Monday Searching, Sorting, and Complexity Analysis Chapter 3