Hashing
Hashing is the concept of converting data of arbitrary size into data of fixed size. A little bit more specifically, we are going to use this to turn strings (or possibly other data types) into integers. This possibly sounds more complex than it is so let's look at an example. We want to hash the expression hello world
, that is, we want to get a numeric value that we could say represents the string.
By using the ord()
function, we can get the ordinal value of any character. For example, the ord('f')
function gives 102. To get the hash of the whole string, we could just sum the ordinal numbers of each character in the string:
>>> sum(map(ord, 'hello world')) 1116
This works fine. However, note that we could change the order of the characters in the string and get the same hash:
>>> sum(map(ord, 'world hello')) 1116
And the sum of the ordinal values of the characters would be the same for the string gello xorld
as well, since g
has an ordinal value which is one less than...