def test_delete(self): """ A deleted k-v pair should not be retrievable. """ h = HashTable(3) h['foo'] = 'bar' h.delete('foo') self.assertEqual(None, h['foo'])
def form_parametrize_delete(): """Forming parameters for testing function delete""" dict_1 = {item: item ** 2 for item in range(100)} dict_2 = HashTable(100) result = [] for i in range(100): dict_1.pop(i) dict_2.delete(str(i)) result.append((dict_2.find(str(i)), bool(dict_1.get(i)))) return result
def test_hash_table(self): hash_table = HashTable(3) hash_table.add("key1", "val1") hash_table.add("key2", "val2") hash_table.add("key3", "val3") hash_table.add("", "val_blank") hash_table.add("key_none", None) hash_table.delete("key2") self.assertEqual("val1", hash_table.get("key1")) self.assertEqual("val_blank", hash_table.get("")) self.assertIsNone(hash_table.get("key_none")) self.assertIsNone(hash_table.get("key2")) self.assertIsNone(hash_table.get("hoge")) self.assertRaises(Exception, hash_table.get, None)
def test_hash_table(): """HashTable test insert, lookup and delete""" table = HashTable() table['AA'] = 465 table.insert('BB', 777) table.insert('CC', 12) table.insert('DD', 99) table.insert('EE', 9999) table.insert('FF', 0) assert 99 in table.lookup("DD") assert 9999 in table["EE"] table.delete('DD') with pytest.raises(KeyError): table.delete('DD')
class HashTableTest(TestCase): def setUp(self): self.hash_table = HashTable(3) def test_insert(self): self.hash_table.insert("1", 1) self.assertEqual(self.hash_table.get("1"), 1) def test_get(self): self.hash_table.insert("1", 1) self.assertEqual(self.hash_table.get("1"), 1) def test_delete(self): self.hash_table.insert("1", 1) self.hash_table.delete("1") self.assertEqual(self.hash_table.get("1"), None)
def test_hash_table(): """Check inserition and deletion""" table = HashTable(10) table.insert('Alex', 3545) table.insert('Sam', 1000) table.insert('John', 1999) table.insert('Max', 9999) table.insert('Nick', 0) assert table.lookup("John") == 1999 assert table.lookup("Max") == 9999 table.delete('Nick') assert table.lookup("Nick") == None with pytest.raises(KeyError): table.delete('Nick')
def test_edge(self): hash_table = HashTable() hash_table.put(0, 12) self.assertEqual(hash_table.get(0), 12) hash_table.put(99991, 13) self.assertEqual(hash_table.get(99991), 13) hash_table.delete(99991) hash_table.delete(0) hash_table.delete(99991) hash_table.delete(0) self.assertEqual(hash_table.get(99991), None) self.assertEqual(hash_table.get(0), None)
def test_delete(self): ht = HashTable() ht.set('I', 1) ht.set('V', 5) ht.set('X', 10) assert ht.length() == 3 ht.delete('I') ht.delete('X') assert ht.length() == 1 with self.assertRaises(KeyError): ht.delete('X') # Key no longer exists with self.assertRaises(KeyError): ht.delete('A') # Key does not exist
obj = HashTable() while terminator == False : print "1 to add" print "2 to delete" print "3 to print" print "6 to terminate" option = input("enter your option\n") if option == 1: item = raw_input("enter the item to be inserted \n") obj.insert(item) elif option == 2: item = raw_input("enter the item to be deleted \n") print "item deleted - "+obj.delete(item) elif option == 3: print obj.print_hash_table() elif option == 6: print "programme is terminated" terminator = True else: print "enter valid option"
class LRUHashTable: def __init__(self, capacity=4): self._length = 0 self._capacity = capacity self._head = DNode() self._tail = DNode() self._head.next = self._tail self._tail.prev = self._head self._hash_table = HashTable() def _add_node(self, node): node.next = self._head.next node.prev = self._head self._head.next.prev = node self._head.next = node def _delete_node(self, node): node.prev.next = node.next node.next.prev = node.prev def delete(self, key): node = self._hash_table.get(key) if node is None: return self._hash_table.delete(key) self._delete_node(node) self._length -= 1 def _move_head(self, node): self._delete_node(node) self._add_node(node) def _pop_tail(self): node = self._tail.prev self._delete_node(node) return node def add(self, key, val): old_node = self._hash_table.get(key) if old_node is not None: old_node.val = val self._move_head(old_node) return node = DNode(key, val) if self._length + 1 > self._capacity: self._pop_tail() self._length -= 1 self._length += 1 self._add_node(node) self._hash_table.put(key, node) def get(self, key): node = self._hash_table.get(key) if node is None: return self._move_head(node) return node.val def __repr__(self): vals = [] curr = self._head while curr: vals.append(str(curr)) curr = curr.next return str(vals)
def test_delete(): obj = HashTable(size=1000) obj.set('name', 'Ardeshir') obj.delete('name') assert obj.get('name') == None
class TestHashTable(unittest.TestCase): def setUp(self): kc1 = [702, 375, 73, 5, 99] self.htc1 = HashTable(0, 20) for i in range(0, len(kc1)): self.htc1.add_collision(self.htc1.insert(Element(kc1[i]))) kc2 = [321, 436, 776, 255, 700, 433, 862, 925, 649, 388] self.htc2 = HashTable(0, 20) for i in range(0, len(kc2)): self.htc2.add_collision(self.htc2.insert(Element(kc2[i]))) kc3 = [ 244, 563, 829, 124, 242, 200, 663, 734, 514, 943, 655, 823, 946, 88, 89 ] self.htc3 = HashTable(0, 20) for i in range(0, len(kc3)): self.htc3.add_collision(self.htc3.insert(Element(kc3[i]))) kc4 = [ 15, 32, 501, 816, 865, 909, 482, 650, 173, 490, 366, 146, 893, 962, 201, 444, 484, 737, 706, 991 ] self.htc4 = HashTable(0, 20) for i in range(0, len(kc4)): self.htc4.add_collision(self.htc4.insert(Element(kc4[i]))) kc5 = [ 356, 948, 840, 755, 335, 256, 1000, 834, 48, 126, 889, 618, 92, 84, 699, 55, 424, 431, 230, 613 ] self.htc5 = HashTable(0, 15) for i in range(0, len(kc5)): self.htc5.add_collision(self.htc5.insert(Element(kc5[i]))) kc6 = [ 364, 736, 874, 391, 345, 357, 523, 968, 712, 472, 942, 146, 930, 761, 729, 991, 635, 517, 27, 329 ] self.htc6 = HashTable(0, 10) for i in range(0, len(kc6)): self.htc6.add_collision(self.htc6.insert(Element(kc6[i]))) kc7 = [ 166, 91, 14, 677, 525, 718, 587, 950, 482, 638, 88, 412, 592, 806, 127, 834, 903, 326, 597, 4 ] self.htc7 = HashTable(0, 5) for i in range(0, len(kc7)): self.htc7.add_collision(self.htc7.insert(Element(kc7[i]))) kid1 = [921, 119, 684, 371, 804] self.htid1 = HashTable(1, 20) for i in range(0, len(kid1)): self.htid1.add_collision(self.htid1.insert(Element(kid1[i]))) kid2 = [233, 6, 407, 135, 899, 187, 645, 40, 98, 853] self.htid2 = HashTable(1, 20) for i in range(0, len(kid2)): self.htid2.add_collision(self.htid2.insert(Element(kid2[i]))) kid3 = [ 276, 311, 957, 133, 404, 233, 301, 254, 619, 965, 430, 369, 272, 294, 378 ] self.htid3 = HashTable(1, 20) for i in range(0, len(kid3)): self.htid3.add_collision(self.htid3.insert(Element(kid3[i]))) kid4 = [ 451, 738, 330, 216, 127, 31, 610, 161, 770, 346, 404, 151, 822, 598, 880, 376, 95, 660, 283, 362 ] self.htid4 = HashTable(1, 20) for i in range(0, len(kid4)): self.htid4.add_collision(self.htid4.insert(Element(kid4[i]))) kid5 = [ 859, 422, 322, 496, 694, 212, 241, 4, 964, 379, 327, 862, 736, 539, 979, 714, 784, 430, 983, 435 ] self.htid5 = HashTable(1, 15) for i in range(0, len(kid5)): self.htid5.add_collision(self.htid5.insert(Element(kid5[i]))) kid6 = [ 239, 701, 798, 416, 922, 232, 929, 788, 349, 344, 975, 73, 941, 208, 768, 287, 600, 55, 78, 782 ] self.htid6 = HashTable(1, 10) for i in range(0, len(kid6)): self.htid6.add_collision(self.htid6.insert(Element(kid6[i]))) kid7 = [ 240, 475, 964, 740, 178, 265, 135, 680, 990, 548, 810, 983, 155, 282, 684, 184, 941, 985, 361, 339 ] self.htid7 = HashTable(1, 5) for i in range(0, len(kid7)): self.htid7.add_collision(self.htid7.insert(Element(kid7[i]))) def test_init_hash_table(self): self.assertEqual(self.htc1.get_collision(), 0) self.assertEqual(self.htc2.get_collision(), 1) self.assertEqual(self.htc3.get_collision(), 6) self.assertEqual(self.htc4.get_collision(), 7) self.assertEqual(self.htc5.get_collision(), 9) self.assertEqual(self.htc6.get_collision(), 10) self.assertEqual(self.htc7.get_collision(), 15) self.assertEqual(self.htid1.get_collision(), 1) self.assertEqual(self.htid1.get_failed_insert(), 0) self.assertEqual(self.htid2.get_collision(), 2) self.assertEqual(self.htid2.get_failed_insert(), 0) self.assertEqual(self.htid3.get_collision(), 8) self.assertEqual(self.htid3.get_failed_insert(), 0) self.assertEqual(self.htid4.get_collision(), 39) self.assertEqual(self.htid4.get_failed_insert(), 0) self.assertEqual(self.htid5.get_collision(), 124) self.assertEqual(self.htid5.get_failed_insert(), 5) self.assertEqual(self.htid6.get_collision(), 117) self.assertEqual(self.htid6.get_failed_insert(), 10) self.assertEqual(self.htid7.get_collision(), 78) self.assertEqual(self.htid7.get_failed_insert(), 15) def test_search(self): self.assertEqual(self.htc1.search(5), (self.htc1.get_cell(5))[0]) self.assertEqual(self.htc2.search(405), None) self.assertEqual(self.htc3.search(734), (self.htc3.get_cell(14))[1]) self.assertEqual(self.htc4.search(32), (self.htc4.get_cell(12))[0]) self.assertEqual(self.htc5.search(46), None) self.assertEqual(self.htc6.search(635), (self.htc6.get_cell(5))[0]) self.assertEqual(self.htc7.search(91), (self.htc7.get_cell(1))[2]) self.assertEqual(self.htid1.search(143), None) self.assertEqual(self.htid2.search(6), self.htid2.get_cell(6)) self.assertEqual(self.htid3.search(276), self.htid3.get_cell(16)) self.assertEqual(self.htid4.search(770), self.htid4.get_cell(14)) self.assertEqual(self.htid5.search(4), self.htid5.get_cell(8)) self.assertEqual(self.htid6.search(768), None) self.assertEqual(self.htid7.search(964), self.htid7.get_cell(4)) def test_delete(self): elc1 = self.htc1.search(5) self.assertEqual(len(self.htc1.get_cell(5)), 1) self.htc1.delete(elc1.get_key()) self.assertEqual(len(self.htc1.get_cell(5)), 0) elc2 = self.htc2.search(388) self.assertEqual(len(self.htc2.get_cell(8)), 1) self.htc2.delete(elc2.get_key()) self.assertEqual(len(self.htc2.get_cell(8)), 0) elc3 = self.htc3.search(734) self.assertEqual(len(self.htc3.get_cell(14)), 2) self.htc3.delete(elc3.get_key()) self.assertEqual(len(self.htc3.get_cell(14)), 1) elc4 = self.htc4.search(32) self.assertEqual(len(self.htc4.get_cell(12)), 1) self.htc4.delete(elc4.get_key()) self.assertEqual(len(self.htc4.get_cell(12)), 0) elc5 = self.htc5.search(948) self.assertEqual(len(self.htc5.get_cell(3)), 3) self.htc5.delete(elc5.get_key()) self.assertEqual(len(self.htc5.get_cell(3)), 2) elc6 = self.htc6.search(635) self.assertEqual(len(self.htc6.get_cell(5)), 2) self.htc6.delete(elc6.get_key()) self.assertEqual(len(self.htc6.get_cell(5)), 1) elc7 = self.htc7.search(91) self.assertEqual(len(self.htc7.get_cell(1)), 4) self.htc7.delete(elc7.get_key()) self.assertEqual(len(self.htc7.get_cell(1)), 3) elid1 = self.htid1.search(684) self.htid1.delete(elid1.get_key()) self.assertEqual(self.htid1.get_cell(4), "Deleted") elid2 = self.htid2.search(6) self.htid2.delete(elid2.get_key()) self.assertEqual(self.htid2.get_cell(6), "Deleted") elid3 = self.htid3.search(276) self.htid3.delete(elid3.get_key()) self.assertEqual(self.htid3.get_cell(16), "Deleted") elid4 = self.htid4.search(770) self.htid4.delete(elid4.get_key()) self.assertEqual(self.htid4.get_cell(14), "Deleted") elid5 = self.htid5.search(4) self.htid5.delete(elid5.get_key()) self.assertEqual(self.htid5.get_cell(8), "Deleted") elid6 = self.htid6.search(344) self.htid6.delete(elid6.get_key()) self.assertEqual(self.htid6.get_cell(7), "Deleted") elid7 = self.htid7.search(964) self.htid7.delete(elid7.get_key()) self.assertEqual(self.htid7.get_cell(4), "Deleted") def test_insert(self): self.assertEqual(len(self.htc1.get_cell(3)), 0) self.htc1.insert(Element(23)) self.assertEqual(len(self.htc1.get_cell(3)), 1) self.assertEqual(len(self.htc2.get_cell(16)), 2) self.htc2.insert(Element(276)) self.assertEqual(len(self.htc2.get_cell(16)), 3) self.assertEqual(len(self.htc3.get_cell(19)), 0) self.htc3.insert(Element(19)) self.assertEqual(len(self.htc3.get_cell(19)), 1) self.assertEqual(len(self.htc4.get_cell(11)), 1) self.htc4.insert(Element(331)) self.assertEqual(len(self.htc4.get_cell(11)), 2) self.assertEqual(len(self.htc5.get_cell(2)), 1) self.htc5.insert(Element(827)) self.assertEqual(len(self.htc5.get_cell(2)), 2) self.assertEqual(len(self.htc6.get_cell(8)), 1) self.htc6.insert(Element(688)) self.assertEqual(len(self.htc6.get_cell(8)), 2) self.assertEqual(len(self.htc7.get_cell(3)), 4) self.htc7.insert(Element(33)) self.assertEqual(len(self.htc7.get_cell(3)), 5) elid1 = Element(18) self.htid1.insert(elid1) self.assertEqual(elid1, self.htid1.get_cell(18)) elid2 = Element(222) self.htid2.insert(elid2) self.assertEqual(elid2, self.htid2.get_cell(2)) elid3 = Element(711) self.htid3.insert(elid3) self.assertEqual(elid3, self.htid3.get_cell(2)) self.htid4.delete(346) elid4 = Element(52) self.htid4.insert(elid4) self.assertEqual(elid4, self.htid4.get_cell(6)) self.htid5.delete(4) elid5 = Element(784) self.htid5.insert(elid5) self.assertEqual(elid5, self.htid5.get_cell(8)) self.htid6.delete(701) elid6 = Element(78) self.htid6.insert(elid6) self.assertEqual(elid6, self.htid6.get_cell(1)) self.htid7.delete(475) elid7 = Element(684) self.htid7.insert(elid7) self.assertEqual(elid7, self.htid7.get_cell(1))
def run(self, winning_score, player_stats: HashTable): """Runs a match, ensuring all scores and names are valid. :param winning_score: The winning score one player must achieve. :param player_stats: The stats of all the remaining players in this round. :return: Winners stats and their score, then the looser stats and their score. """ if self.player_name_a is not None and self.score_a is None: # Validate players, both must still be able to play this round. self.player_name_a = self.ensure_player_exists( self.player_name_a, player_stats) # Prevent players playing any more matches this round, and load their # relevant tournament stats for returning later. player_stats_a = player_stats.delete(self.player_name_a) self.player_name_b = self.ensure_player_exists( self.player_name_b, player_stats) self.ensure_players_compatible(player_stats) player_stats_b = player_stats.delete(self.player_name_b) print('%s vs %s' % (self.player_name_a, self.player_name_b)) self.score_a = next_int("Enter %s's score" % self.player_name_a) self.score_b = next_int("Enter %s's score" % self.player_name_b) elif self.player_name_a is not None: # Validate players, both must still be able to play this round. self.player_name_a = self.ensure_player_exists( self.player_name_a, player_stats) # Prevent players playing any more matches this round, and load their # relevant tournament stats for returning later. player_stats_a = player_stats.delete(self.player_name_a) self.player_name_b = self.ensure_player_exists( self.player_name_b, player_stats) self.ensure_players_compatible(player_stats) player_stats_b = player_stats.delete(self.player_name_b) else: self.player_name_a = next_string('Enter player A') self.player_name_a = self.ensure_player_exists( self.player_name_a, player_stats) player_stats_a = player_stats.delete(self.player_name_a) self.score_a = next_int('Enter score A') self.player_name_b = next_string('Enter player B') self.player_name_b = self.ensure_player_exists( self.player_name_b, player_stats) self.ensure_players_compatible(player_stats) player_stats_b = player_stats.delete(self.player_name_b) self.score_b = next_int('Enter Score B') # Validate scores: # - Only one may be a winner. # - Both must be no bigger than the winning score. # - Both must be no smaller than zero. self.validate_scores(winning_score) # Find and return the winner and loser with their scores. if self.score_a > self.score_b: return player_stats_a, self.score_a, player_stats_b, self.score_b else: return player_stats_b, self.score_b, player_stats_a, self.score_a
class Set: def __init__(self, elements=None): # Initialize a empty hash table self.hash_table = HashTable() if elements: for element in elements: self.add(element) # Add the item to the set if it doesn't exist def __str__(self): """Return a formatted string representation of this set.""" items = ['({!r})'.format(item) for item in self.hash_table.keys()] return ''.join(items) def __iter__(self): """Make the set iterable and return the keys of the items""" for item in self.hash_table.keys(): yield item def __repr__(self): """Return a string representation of this linked list.""" return '({!r})'.format(self.hash_table.keys()) def size(self): """Return an integer representing the size to the set Time Complexity: O(1) because the alternate length method in the hash table""" return self.hash_table.size def contains(self, element): """Returning a boolean indicating whether the hash table has the element already Time Complexity: O(L) where L is the number of item in the indexed bucket""" return self.hash_table.contains(element) def add(self, element): """Add an element to set if its unique Time Complexity: O(l) where L is the number of item in the indexed bucket""" self.hash_table.set(element, None) # O(L) def remove(self, element): """Remove the element from the set, Raise KeyError is not found Time Complexity: O(l) where L is the number of item in the indexed bucket""" if self.hash_table.contains(element): # O(L) self.hash_table.delete(element) # O(L) else: raise KeyError('Element not found:'.format(element)) def union(self, other_set): """Assuming the input is a Set object, use iterable to make union easier Return a new set that is a union of this set and other set Time Complexity: O(n + m) -> O(n) because it is O(n) to create a new set and O(m) for add elements from other set""" union_set = Set(self) # O(n) where n is the number of elements in the set # Initialize a new set that has all the elements from itself for item in other_set: # O(m) where m is the number of elements in the other set union_set.add(item) # O(L) return union_set def intersection(self, other_set): """Assuming the input is a Set object Return a new set that only contains the common elements between two sets Time Complexity: O(min(n,m)) because it has to compare all elements from smaller set""" intersection_set = Set() # Initialize a new empty set O(1) # Determining which sets is bigger if other_set.size() >= self.size(): # O(1) bigger_set = other_set # O(1) smaller_set = self # O(1) else: bigger_set = self # O(1) smaller_set = other_set # O(1) for item in smaller_set: # item = key if bigger_set.contains(item): # O(1) intersection_set.add(item) # O(1) return intersection_set def symmetric_difference(self, other_set): """Assuming the input is a Set object Return a new set that only contains the difference elements between two sets Time Complexity: O(n + m) -> O(n) because it is O(n) to create a new set and O(m) for add elements from other set TODO: How can I improve this? """ # Formula: union - intersection = difference union_set = self.union(other_set) # O(n) inter_set = self.intersection(other_set) # O(n) # This is not efficient for element in inter_set: # O(n) if union_set.contains(element): # O(1) union_set.remove(element) # O(1) return union_set def difference(self, other_set): """Assuming the input is a Set object Return a set of the of the base set minus the intersection of the other set Time Complexity: O(n) where n is the number of elements in self""" new_set = Set() for element in self: # O(n) if other_set.contains(element) is False: # O(1) new_set.add(element) # O(1) return new_set def is_subset(self, other_set): """Assuming the input is a Set object Return a boolean indicate whether the base has all the elements of the other set Time Complexity: O(n) where n is the number of elements in the other set""" # Making sure the other set is smaller than the base set if other_set.size() > self.size(): # O(1) return False if other_set.size() == 0: # O(1) return True counter = 0 for element in other_set: # O(n) if self.contains(element): # O(1) counter += 1 return counter == other_set.size() # O(1)