Wednesday, 6 April 2016

Week 12

It's the final week of class and we're ending the course with hash tables and traps - sticky bits of code that look, at first, unproblematic, but end up producing errors or wildly unexpected results. I was excited to learn about hash tables, mostly because I had gotten endless error messages from python this year saying such-and-such data type was not hashable and I never understood what it meant. Now it finally makes sense to me. Hash tables simply assign some piece of data a unique number so that when we want to find that data again we can do so immediately just by knowing its unique address. A hashable data type is just a python Type that can be assigned a unique number (hence the data type needs to be immutable). In discussing hash tables we learned about the birthday paradox - that, given 366 possible birth dates, after looking through about 23 of these dates we are about 50% likely to find a recurring date. And that is the major problem with hash tables - in assigning unique numbers to data we are always bound to assign the same number twice eventually. There is no formula we can come up with to avoid this. So, our code must take measures to avoid this, and usually this means increasing the size of the hash table so that it is always significantly larger than the amount of data that currently has been hashed (assigned a unique number).
We also learned about a few interesting traps in python. One has to do with "global" variables. If we create some variable x outside of the function and then call x inside the function before defining it locally inside the function, then you will get an error saying x was referenced before it was created. This is because inside every function variables act as if they are all local, so to get around this you either need to create a local variable inside your function or define the variable x as a global variable inside your function.
Finally, the most interesting trap I thought had to do with creating default values in a function. Apparently if you set a default value equal to a mutable data type, like a list, then when that function is called a second time, or any time after its first call, the default value of our list will now be equal to whatever state the list was last in. In other words, say we have a parameter A that we want to have the default value of an empty list, so A = []. If after we run the function the first time A now equals [3] then when we call the function next we will not get a default value of A = [] but A = [3]. This happens for all mutable data types! So the big lesson: NEVER use mutable data types as default values for function parameters.
Well, the semester is coming to an end, all that's left is to study for finals...

No comments:

Post a Comment