Last active
May 7, 2016 16:17
-
-
Save imxdn/076cbaf8e90eb5317b286d416372b515 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class HashTable: | |
| def __init__(self, size): | |
| self.size = size | |
| self.slots = [None] * size | |
| self.data = [None] * size | |
| def insert(self, key, data): | |
| hashval = self._hash(key) | |
| if self.slots[hashval] == None: | |
| self.slots[hashval] = key | |
| self.data[hashval] = data | |
| print("Insertion successful") | |
| else: | |
| print("Slot already occupied!") | |
| def search(self, key): | |
| hashval = self._hash(key) | |
| if self.slots[hashval] != None: | |
| print("Item found {} with key value {}".format(self.data[hashval], key)) | |
| else: | |
| print("Key not found") | |
| def _hash(self, key): | |
| ''' | |
| If key is a string, sum up the ASCII values of each character and mod by number of slots | |
| else if an integer, mod with directly with number of slots. | |
| ''' | |
| if type(key) == int: | |
| hv = key%(self.size) | |
| return hv | |
| else: | |
| sum = 0 | |
| for _ in range(0, len(key)): | |
| sum += ord(key[_]) | |
| hv = sum%(self.size) | |
| return hv | |
| H = HashTable(11) | |
| while(True): | |
| ch = int(input(""" | |
| (1) Insert | |
| (2) Search | |
| (3) Quit | |
| """)) | |
| if ch == 1: | |
| key, data = input("Enter key,data: ").split(',') | |
| H.insert(key, data) | |
| elif ch == 2: | |
| key = input("Enter the key to search: ") | |
| H.search(key) | |
| elif ch == 3: | |
| quit() | |
| else: | |
| print("Invalid choice, please try again...") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment