#Implement a hash table using only arrays - in python, java class HashTable(object): def __init__(self): self.size = 100 self.value_array = [] self.total_entries = 0 for i in range(100): self.value_array.append(None) def __str__(self): output_lines = [] for item in self.value_array: if item != None: output_lines.append("Key: " + str(item[0]) + " Value: " + str(item[1])) return "\n".join(output_lines) def resize(self): new_value_array = [] new_size = 2 * self.size for i in range(self.size*2): new_value_array.append(None) for i in range(self.size): if self.value_array[i] != None: self.add_internal(self.value_array[i][0], self.value_array[i][1], new_value_array, new_size, True) self.value_array = new_value_array self.size = new_size def probe(self, key, position): # does the position have this key? return self.value_array[position] != None and self.value_array[position][0] == key def add(self, key, value): self.add_internal(key, value, self.value_array, self.size) def add_internal(self, key, value, value_array, size, during_resize = False): if value_array[self.hash1(key)] == None: value_array[self.hash1(key)] = key, value else: #find the next slot added = False attempt_count = 1 while (not added): newhash = (self.hash1(key) + attempt_count*self.hash2(key)) % size if value_array[newhash] == None: value_array[newhash] = key, value added = True else: attempt_count += 1 if not during_resize: self.total_entries += 1 if self.total_entries > size/2: self.resize() def remove(self, key): print "Failure - not implemented - remove" def get(self, key): got_value = self.value_array[self.hash1(key)] if got_value == None: return None retrieved_key, retrieved_value = got_value if retrieved_key != key: found = False attempt_count = 1 while (not found and attempt_count < 50): newhash = (self.hash1(key) + attempt_count*self.hash2(key)) % self.size value_at_hash = self.value_array[newhash] if value_at_hash != None: retrieved_key, retrieved_value = value_at_hash if retrieved_key == key: found = True attempt_count += 1 else: attempt_count += 1 return retrieved_value def hash1(self, key): return id(key) % self.size def hash2(self, key): hashval = (id(key) + 501) % self.size return hashval def test_hashtable(): ht = HashTable() ht.add("Meo", "Smith") ht.add("Kaga", "Garka") assert ht.get("Kaga") == "Garka" assert ht.get("Hitler") == None for i in range(250): ht.add(i,i*i) for i in range(250): print i print ht.get(i) # assert ht.get(i) == i*i print ht print "Passed all tests" test_hashtable()
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question