Feb 7
Comments on last week's homework have been posted.
The next homework, due Thursday, is up. What we'll do today is closely related.
We're talking now about "data structures" - what they are and some examples.
Questions about anything in the reading?
The code that I wrote in class is attached:
- indexedarray.py
- linkedlist.py
- stack.py
array vs list
Consider the following two types of data sequences.
- An "indexed array" is an index storage mechanism, a[0], a[1], a[2] etc.
- A "linked list" is a pointer storage mechanism, a.next -> b, b.next -> c, etc.
Linked lists come in two kinds: singly linked or doubly linked
a -> b -> c -> d single link (a.next, b.next : forward only)
|a| -> |b| -> |c| double link (b.next, b.previous: both directions)
| | <- | | <- | |
As an "abstract data type", we could build either of these as python classes.
a = IndexedArray()
b = LinkedList()
What methods (i.e. what API) would be needed for these?
stack
Now consider the "stack" data structure (i.e. python class with an API) that
can do these sorts of things:
s = Stack() # create an empty one
s.push(5) # do something to it: put data into it. Return: nothing.
s.push(10) # do something to it: put more data into
s.size() # return the number of things in it; leave it unchanged
s.pop() # return a piece of it (which?); remove it from the stack.
Can we get an arbitrary piece of data? Answer: no.
Is this the same as a python list? Answer: no. Python lists are more powerful.
Why would we want one of these? Answer: for some sorts of algorithms, this kind of storage is enough. Python lists may be too slow or too memory intensive, depending on the situation.
Each of these operations will have a O() behavior. For really huge amounts of data, which sort of storage you want will depend on what sorts of operations you expect to do most often.
implementation
Can we implement a stack by using an array? Answer: yes.
Can we implement a stack by using a linked list? Answer: yes.
Which is better? Answer: it depends.
Can we implement an indexed array by using a linked list? Answer: yes, but it will be slow - not something you would usually want to do.
in class coding
We're going to do some of this now.
For homework, I've asked you to implement a Stack and a Queue
using a DoublyLinkedList or at least the ideas of a linked list.
So as a step in that direction, I want to write (a) a LinkedList class, and (b) an Array class.
And perhaps implement the Array class several different ways.
We also want to do this right: that means docs & tests, eh?
... more in class.