Apr 23
old business - dynamic programming (i.e. recursion with remembering)
Discuss the "making change" homework assignment:
Given a set of coin denominations (1,5,10)=(penny,nickel,dime)
or (1,6,10)=(funky), find the minium number of coins
needed to make 24 cents.
Describe how to do this in three different algorithm design patters:
- brute force (gives correct answer; slow)
- greedy (fast but not always correct)
- dynamic programming (fast and correct but often harder to design)
future business
End of term projects are going to be due soon.
I would like to have you present them on the last
day of classes ... which is two weeks from today.
Weekly homework will be less from now onwards,
to give you time to work on these projects. Please use
the time wisely, and start now.
Next week: either 'hard' problems & heuristics (text chap 9)
or public/private key crypto (something completely different,
somewhat related to the hash functions this week).
I'm open to your thoughts.
new business - hash tables a.k.a. 'dictionaries' in python
context
We've looked at several data structures this term which make implementing the various algorithms simpler:
- stack
- queue
- heap (priority queue)
All of these are built upon the basic C memory model : a block of addressable memory data[i] where i is an integer.
One important data structure that we've used but not discussed in any detail is the "hash table", which gives O(1) lookup.
basic ideas
- in python called 'dictionaries'
- in javascript called 'objects'
- sometimes called 'associative arrays'
- O(1) (or nearly so) lookup of based on a key
The basic idea is that we use a regular linear array data[i],
but compute the number i using a particular function called a "hash function" or just a "hash". Then for some key, the index i is hash(key) and we store the value at data[hash(key)]. (Actually, the hash value is often much bigger than the allocated storage, so we actually store things at "i = hash(key) mod size_of(array) ".
Terminology:
- hash table : the array
- hash function : a function mapping keys to integers
- collision : when two different keys hash to the same integer
Unless the hash function is "perfect" (unlikely),
there will sometimes be collisions. There are a variety
of tricks to handle these cases - see the wikipedia article for the details.
hash function code
I have some python code to look at the hash function idea;
see
hashes.