Hashing

Hashing is a concept in which, when we give data of an arbitrary size to a function, we get a small simplified value. This function is called a hash functionHashing uses a hash function that maps the given data to another range of data, so that a new range of data can be used as an index in the hash table. More specifically, we will use hashing to convert strings into integers. In our discussions in this chapter, we are using strings to convert into integers, however, it can be any other data type which can be converted into integers. Let's look at an example to better understand the concept. We want to hash the expression hello world, that is, we want to get a numeric value that we could say represents the string.

We can obtain the unique ordinal value of any character by using the ord() function. For example, the ord('f') function gives 102. Further, to get the hash of the whole string, we could just sum the ordinal numbers of each character in the string. See the following code snippet:

>>> sum(map(ord, 'hello world'))
1116

The obtained numeric value, 1116, for the whole hello world string is called the hash of the string. Consider the following diagram to see the ordinal value of each character in the string that results in the hash value 1116

The preceding approach is used to obtain the hash value for a given string and seems to work fine. However, note that we could change the order of the characters in the string and we would have got the same hash; see the following code snippet where we get the same hash value for the world hello string:

>>> sum(map(ord, 'world hello'))
1116

Again, there would be the same hash value for the gello xorld string, as the sum of the ordinal values of the characters for this string would be the same since g has an ordinal value that is one less than that of h, and x has an ordinal value that is one greater than that of w. See the following code snippet:

>>> sum(map(ord, 'gello xorld'))
1116

Look at the following diagram, where we can observe that the hash value for this string is again, 1116:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset