def test_can_set_and_get_basic_case(self): hashmap = HashMap() self.assertEqual(hashmap._number_of_elements, 0) hashmap.set('key', 'val') self.assertEqual(hashmap._number_of_elements, 1) self.assertEqual(hashmap.get('key'), 'val') self.assertIsNone(hashmap.get('otherval'))
def test_key_present(self): hm = HashMap() self.assertEqual(hm.get("asdf"), None) self.assertEqual(hm.get("asdf", 0), 0) hm.set("qwerty", 12345) self.assertEqual(hm.get("qwerty"), 12345) self.assertEqual(hm.size(), 1) self.assertEqual(hm.capacity(), 8)
class Environment(object): def __init__(self): self.__objects = [] # World objects self.__hashmap = HashMap() def addObject(self, object): """ Add an object to the environment """ object.setEnvironment(self) self.__objects.append(object) def removeObject(self, object): """ Remove an object from the environment """ self.__objects.remove(object) def step(self, time): """ Step forward with controllers attached to each object """ for object in self.__objects: object.processControllers(time) # After processing the controllers, check for collisions self.checkCollisions() def inputStep(self, mouse_x, mouse_y): """ Pass inputs to the objects """ for object in self.__objects: object.mouseEvent(mouse_x, mouse_y) #TODO: Add a keyboard event here def addBlock(self, x, y): self.__hashmap.insert((x, y)) def clearMap(self): self.__hashmap.clear() def checkCollisions(self): position = self.__objects[0].getPosition() print "Character position: ", position.x, position.y print "Hash output: ", self.__hashmap.get((position.x, position.y)) if self.__hashmap.get((position.x, position.y)): print "collision!" self.__objects[0].gravity.stop() self.__objects[0].gravity.reset() self.__objects[0].jump.stop() else: self.__objects[0].gravity.start()
def test_can_set_and_get_multiple_values(self): hashmap = HashMap() self.assertEqual(hashmap._number_of_elements, 0) hashmap.set('key', 'val') self.assertEqual(hashmap._number_of_elements, 1) self.assertEqual(hashmap.get('key'), 'val') hashmap.set('otherkey', 'otherval') self.assertEqual(hashmap._number_of_elements, 2) self.assertEqual(hashmap.get('otherkey'), 'otherval') self.assertEqual(hashmap.get('key'), 'val') self.assertIsNone(hashmap.get('blah'))
def test_remove(): hm = HashMap() keys = [(r, r) for r in (range(10))] values = list(range(1, 11)) for k, v in zip(keys, values): hm.set(k, v) hm.remove((3, 3)) print(hm) with pytest.raises(KeyError): hm.get((3, 3)) assert hm.get((5, 5)) == 6
def test_ten_keys(self): hm = HashMap() keys = ["first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth"] values = list(range(1, 11)) for i in range(len(keys)): hm.set(keys[i], values[i]) self.assertEqual(hm.get("sixth"), 6) self.assertNotEqual(hm.get("sixth"), 7) self.assertNotEqual(hm.get("sixth"), 5) hm.set("third", 409) self.assertEqual(hm.get("third"), 409) self.assertEqual(hm.size(), 10) self.assertEqual(hm.capacity(), 16)
def test_get_set(): hm = HashMap() with pytest.raises(KeyError): hm.get((0, 0)) keys = [(r, r) for r in (range(10))] values = list(range(1, 11)) for k, v in zip(keys, values): hm.set(k, v) assert hm.get((5, 5)) == 6 assert hm.get((9, 9)) == 10 hm.set((2, 2), 409) assert hm.get((2, 2)) == 409
def main(): ''' driver for project ''' hash_map = HashMap() with open("AliceInWonderland.txt", encoding='utf8') as input_file: for raw_line in input_file: words = clean_line(raw_line) for word in words: hash_map.set(word, hash_map.get(word, 0) + 1) keys = hash_map.keys() key_values = [(key, hash_map.get(key)) for key in keys] key_values.sort(reverse=True, key=lambda x: x[1]) print("The most common words are:") for element in key_values[:15]: print(f'{element[0]}\t\t{element[1]}') print()
def test_can_set_and_get_many_values(self): hashmap = HashMap() for number in range(0, 20): key, val = str(number), number hashmap.set(key, val) self.assertEqual(hashmap._number_of_elements, 20) for number in range(0, 20): key, expected_val = str(number), number self.assertEqual(hashmap.get(key), expected_val)
class DictionaryTable: __slots__ = 'hash_table' def __init__(self, hash_function, initial_size=10, max_load_factor=0.7): """ This function is used to initialize the hashtable based on the hashfunction provided with a certain load factor which is used to increase the size of the hash table :param hash_function: a particular hash value calculating function :param initial_size: initial size of the table :param max_load_factor: loac factor for a table """ self.hash_table = HashMap(initsz=initial_size, hash_func=hash_function, maxload=max_load_factor) def process_file(self, file_name): """ This function is used to take input of words from the file with a provided filename :param file_name: name of the file along with the extension :return: None """ with open(file_name) as file_pointer: for each_line in file_pointer: each_line = each_line.strip() list_of_words = re.split('\W+', each_line) for word in list_of_words: if len(word) > 0: self.count_frequency(word.lower()) def count_frequency(self, word): """ This function is used to keep the count of repetative words given in a particular file :param word: current word to check the count of :return: None """ try: self.hash_table.put(word, self.hash_table.get(word) + 1) except KeyError: self.hash_table.put(word, 1) def print_hash_table(self): """ This function is used to make a call to the print_map function print the entire hash table :return: None """ self.hash_table.print_map() def get_max_occurred_word(self): """ This method is used to return the word with maximum count :return: word which occured maximum time in a particular file """ element = Entry(None, 0) for named_tuple in self.hash_table.table: if named_tuple is not None: if named_tuple.value > element.value: element = named_tuple return element
class HashMapTests(unittest.TestCase): def setUp(self): self.hashmap = HashMap() def tearDown(self): self.hashmap = None # test if empty hashmap is empty def test_initialize_hashmap(self): self.assertTrue(self.hashmap.is_empty()) self.assertEqual(len(self.hashmap), 0) # test adding key into hashmap and getter method def test_insert_into_hashmap(self): self.assertFalse(self.hashmap.has_key("randomValue")) self.hashmap["FirstKey"] = "FirstValue" self.assertTrue(self.hashmap.has_key("FirstKey")) self.assertEqual(len(self.hashmap), 1) # test updating key in hashmap def test_update_in_hashmap(self): self.hashmap["FirstKey"] = "FirstValue" self.hashmap["SecondKey"] = "SecondValue" self.assertEqual("FirstValue", self.hashmap["FirstKey"]) # test deleting key in hashmap def test_delete_in_hashmap(self): self.hashmap["FirstKey"] = "FirstValue" self.hashmap.delete("FirstKey") self.assertFalse(self.hashmap.has_key("FirstKey")) self.assertIsNone(self.hashmap.get("FirstKey")) # test sections grow with an increase in # of key/values def test_hashmap_resize(self): self.assertEqual(6, self.hashmap.num_sections()) i = 1 while i <= 7: self.hashmap[i] = i i += 1 self.assertEqual(12, self.hashmap.num_sections()) # test for other hashmap to update old hashmap def test_hash_map_updates_with_other_hashmap(self): self.hashmap["FirstKey"] = "FirstValue" other_hashmap = HashMap() other_hashmap["FirstKey"] = "OtherFirstValue" other_hashmap["SeondKey"] = "SecondValue" self.hashmap.update(other_hashmap) self.assertEqual("OtherFirstValue", self.hashmap["FirstKey"])
class TestHashMapFunctions(unittest.TestCase): def setUp(self): self._ref = {} self._map = HashMap() def add(self, key, value): self._ref[key] = value self._map[key] = value def delete(self, key, value): del self._ref[key] del self._map[key] def test_add(self): for i in xrange(100): self.add("key_"+str(i), "value_"+str(i)) self.assert_ref_equals_map() def test_delete(self): for i in xrange(100): self.add("key_"+str(i), "value_"+str(i)) for i in xrange(0, 100, 2): self.delete("key_"+str(i), "value_"+str(i)) self.assert_ref_equals_map() def test_get(self): for i in xrange(100): self.add("key_"+str(i), "value_"+str(i)) for i in xrange(100): self.assertEqual(self._ref["key_"+str(i)], self._map["key_"+str(i)]) def test_random(self): import random for i in xrange(10000): r = random.randint(0, 2) key = "key_"+str(random.randint(0, 9)) value = "value_"+str(random.randint(0, 9)) if r == 0: self.add(key, value) elif r == 1 and self._ref.get(key, None) is not None: self.delete(key, value) else: self.assertEqual(self._ref.get(key, None), self._map.get(key, None)) def assert_ref_equals_map(self): self.assertItemsEqual(self._ref.keys(), self._map.keys()) self.assertItemsEqual(self._ref.values(), self._map.values())
def test_put_and_get(self): # New HashMap object HM = HashMap() # For Normal Inputs # Putting Value self.assertTrue(HM.put(1, "one")) self.assertTrue(HM.put(2, "two")) # Getting value self.assertEquals(HM.get(1), "one") self.assertEquals(HM.get(2), "two") # For Inputs with colliding hash values # Putting values self.assertTrue(HM.put(3, "three")) self.assertTrue(HM.put(25, "twenty-five")) self.assertTrue(HM.put(36, "thirty-six")) self.assertTrue(HM.put(47, "forty-seven")) # Getting values self.assertEquals(HM.get(3), "three") self.assertEquals(HM.get(25), "twenty-five") self.assertEquals(HM.get(36), "thirty-six") self.assertEquals(HM.get(47), "forty-seven") # For inserting different values for same key # Putting value self.assertTrue(HM.put(4, "four")) # Getting value self.assertEquals(HM.get(4), "four") # Putting a different value self.assertTrue(HM.put(4, "four-again")) # Getting value self.assertTrue(HM.get(4), "four-again") # Getting a value not in hashmap self.assertFalse(HM.get(5), "five") # Getting value previously declared self.assertTrue(HM.get(4), "four-again")
def get_scene_find_xml(xml, scene_id): """ 解析XML,判断是否有重复的监控项,如果正常保存场景与监控项的关联关系 :param xml: :param scene_id: :return: """ root_a = ElementTree.XML(xml) parent = root_a.find("root", "mxGraphModel") list = parent._children # 判断绑定的监控项是否有重复 items_map = HashMap() # 批量入库数组 add_scene_item_list = [] for dto in list: if dto.tag == "object": dto_item_id = str(dto.attrib.get("item_id")) # 关联的监控项id非数字直接进入下一个循环 if dto_item_id.isdigit() is False: continue int_item_id = int(dto_item_id) item_name = str(dto.attrib.get("label")) # 添加了重复的监控项,直接返回提示 if items_map.get(int_item_id) is not None: return item_name items_map.add(int_item_id, item_name) temp_dto = Scene_monitor.objects.filter(scene_id=scene_id, item_id=int_item_id) if temp_dto.count() == 0: # 只有等于零时才新增 scene_dto = Scene_monitor() scene_dto.item_id = int_item_id scene_dto.scene_id = scene_id scene_dto.x = 0 scene_dto.y = 0 scene_dto.scale = 0.0 scene_dto.score = 0 scene_dto.order = 0 add_scene_item_list.append(scene_dto) # scene_dto.save() print "场景 " + str(scene_id) + " " + dto_item_id + "保存成功" else: print "场景 " + str(scene_id) + " " + dto_item_id + "已存在,不处理" # 如果数组不为空,执行批量入库 if add_scene_item_list.__len__() > 0: Scene_monitor.objects.bulk_create(add_scene_item_list) return "true"
def main(): """ Main driver to run program. """ hashmap = HashMap() text_file = open("AliceInWonderland.txt", "r", encoding="utf8") for line in text_file: temp = clean_line(line) for word in temp: if hashmap.contains(word) is True: tempvalue = hashmap.get(word) hashmap.set(word, (tempvalue + 1)) else: hashmap.set(word, 1) hashmap.print_top() text_file.close()
def checkMintorDir(app_dir, mintor_dir_path, mintor_md5_filepath): print "checkMintorDir()...%s from file: %s where module is:%s" % ( mintor_dir_path, mintor_md5_filepath, app_dir) if not app_dir or not mintor_dir_path or not mintor_md5_filepath: print "###########ERROR###############" print "checkMintorDir param error app_dir:%s mintor_dir_path:%s mintor_md5_filepath:%s" % ( app_dir, mintor_dir_path, mintor_md5_filepath) return pass # 读区已经压缩过文件和md5到hashmap md5HashMap = HashMap() if os.path.exists(mintor_md5_filepath): for line in open(mintor_md5_filepath): # print line line = line.replace('\r', '').replace('\n', '').replace('\t', '') lineItems = line.rsplit('--MD5-->', 2) #print "%s %s" %(lineItems[0],lineItems[1]) md5HashMap.add(lineItems[0], lineItems[1]) pass else: f = open(mintor_md5_filepath, 'w') f.close() pass # 遍历被监控的文件夹,计算新的md5值和老的md5Hashmap值是否相等 for dirpath, dirnames, filenames in os.walk(mintor_dir_path): # print "dirpath:%s dirnames:%s filenames:%s" %(dirpath,dirnames,filenames) # if "build" not in dirpath and "intermediates" not in dirpath and "generated" not in dirpath and "outputs" not in dirpath and "gen" not in dirpath: # continue for file in filenames: fullpath = os.path.join(dirpath, file) simplepath = fullpath.replace(app_dir, '') if simplepath and simplepath.startswith('/'): simplepath = simplepath[1:len(simplepath)] pass # print "this is: %s" %simplepath # 9.png 压缩了之后不能缩放 if simplepath.endswith(".9.png"): print "ignore: %s" % simplepath elif simplepath.endswith(".png") or simplepath.endswith(".jpg"): oldMd5 = None try: oldMd5 = md5HashMap.get(simplepath) except KeyError, e: pass md5 = util.generateMd5_2(fullpath) print "\ncompressing %s oldMd5:%s md5:%s" % (simplepath, oldMd5, md5) if cmp(oldMd5, md5) == 0: print "%s is already compressed!!! skiped" % simplepath else: if JUST_CHECK: title = "you have picture not compressed yet!!!" content = "please local run:python lcba/lintCompress.py to compress Resources!!!" print title print content glo.set_value('_reason', title) glo.set_value('_title', title) glo.set_value('_content', content) util.safeQuit(None, None) pass # 2,上传tinypng压缩图片 compressSinglePicLogic(fullpath, fullpath + ".tiny", simplepath, mintor_md5_filepath) pass pass pass
def test_get_uses_default_when_key_not_present(self): hashmap = HashMap() hashmap['key'] = 'val' self.assertEqual(hashmap.get('key'), 'val') self.assertEqual(hashmap.get('key2', 'default'), 'default') self.assertEqual(hashmap.get('key2', 'blah'), 'blah')
#!/usr/bin/python # -*- coding: utf-8 -*- from hashmap import HashMap h = HashMap(4) # 4 cells h.add("erkan", "444-44-44") h.add("maxime", "333-33-33") h.add("bob", "555-55-55") h.add("mike", "666-66-66") h.add("aude", "777-77-77") h.add("kosta", "888-88-88") h.get("mike") h.delete("bob") h.show()
class HashMapTest(unittest.TestCase): def setUp(self): self.hashmap = HashMap() def populate(self, values): for value in values: self.hashmap.put(*value) def remove(self, values): for value in values: self.hashmap.remove(value) def test_put(self): # Can add to hashmap self.hashmap.put('Apples', 5) self.assertEqual(self.hashmap.get('Apples'), 5) # Size should increase with added elements self.assertEqual(self.hashmap.size(), 1) # Hashmap should no longer be marked as empty self.assertEqual(self.hashmap.is_empty(), False) # Should still work with multiple items added fruits = [('Oranges', 1), ('Pineapples', 10), ('Mangos', 7), ('Grapefruit', 9), ('Avocado', 53), ('Blueberry', 16), ('Strawberries', 42), ('Cherries', 21), ('Durian', 18), ('Guava', 99), ('Blackberries', 53), ('Cranberries', 42)] self.populate(fruits) # All inputted items should be retrievable for fruit in fruits: self.assertEqual(self.hashmap.get(fruit[0]), fruit[1]) self.assertEqual(self.hashmap.size(), len(fruits) + 1) # Should be able to override pre-existing values self.hashmap.put('Apples', 20) self.assertEqual(self.hashmap.get('Apples'), 20) # Should not increase hashmap size self.assertEqual(self.hashmap.size(), len(fruits) + 1) def test_remove(self): # Should work if hashmap contains only one element in bucket self.hashmap.put('Apples', 15) self.hashmap.remove('Apples') self.assertEqual(self.hashmap.get('Apples'), None) fruits = [('Oranges', 1), ('Bananas', 2), ('Pineapples', 10), ('Mangos', 7)] self.populate(fruits) # Should remove pre-existing element self.hashmap.remove('Bananas') self.assertEqual(self.hashmap.get('Bananas'), None) # Size should decrease self.assertEqual(self.hashmap.size(), len(fruits) - 1) for fruit in fruits: self.hashmap.remove(fruit[0]) # Hash Map should be empty self.assertEqual(self.hashmap.size(), 0) self.assertEqual(self.hashmap.is_empty(), True) def test_resize(self): # Initialize HashMap with Initial Capacity of 4 self.hashmap = HashMap(4) self.assertEqual(self.hashmap.capacity(), 4) fruits = [('Oranges', 1), ('Bananas', 2), ('Pineapples', 10), ('Mangos', 7)] self.populate(fruits) # Hashmap should double in capacity self.assertEqual(self.hashmap.size(), 4) self.assertEqual(self.hashmap.capacity(), 8) # Items should still be accessible for fruit in fruits: self.assertEqual(self.hashmap.get(fruit[0]), fruit[1]) for fruit in fruits: self.hashmap.remove(fruit[0]) # Hashmap should halve in size self.assertEqual(self.hashmap.capacity(), 4) def test_mixed_calls(self): fruits = [('Oranges', 1), ('Pineapples', 10), ('Mangos', 7), ('Grapefruit', 9), ('Avocado', 53), ('Blueberries', 16), ('Strawberries', 42), ('Cherries', 21), ('Durian', 18), ('Guava', 99), ('Blackberries', 53), ('Cranberries', 42)] self.populate(fruits) # Hashmap capacity should increase self.assertEqual(self.hashmap.capacity() > 8, True) fruits_to_remove = {'Grapefruit', 'Cherries', 'Guava', 'Oranges'} # Remove fruits from hashmap for fruit in fruits_to_remove: self.hashmap.remove(fruit) # Checks to make sure they are all deleted self.remove(fruits_to_remove) remaining = len(fruits) - len(fruits_to_remove) self.assertEqual(self.hashmap.size(), remaining) # Make sure all other fruits are still fine for fruit, val in fruits: if fruit in fruits_to_remove: continue self.assertEqual(self.hashmap.get(fruit), val) # Add some more fruits additional_fruits = [('Longan', 32), ('Pomegranate', 82), ('Papaya', 92)] self.populate(additional_fruits) # Size should update accordingly new_size = remaining + len(additional_fruits) self.assertEqual(self.hashmap.size(), new_size) # Updating some existing fruit values updates = [('Papaya', 53), ('Cranberries', 32), ('Durian', 9)] self.populate(updates) # Size should not increase self.assertEqual(self.hashmap.size(), new_size) additional_fruits_to_remove = { 'Longan', 'Pomegranate', 'Papaya', 'Strawberries', 'Blueberries', 'Blackberries', 'Durian', 'Cranberries' } fruits_to_remove = fruits_to_remove.union(additional_fruits_to_remove) self.remove(fruits_to_remove) # Hashmap size should be a quarter of its capacity, capacity should halve self.assertEqual(self.hashmap.capacity(), 8)
from hashmap import HashMap my_dict1 = HashMap(100, probing='quadratic') my_dict1.set('animal', 'lion') print("obj=mydict1, key = animal, value = %s" % my_dict1.get('animal')) my_dict2 = HashMap(10, 'linear') my_dict2.set('animal', 'monkey') print("obj=mydict2, key = animal, value = %s" % my_dict2.get('animal'))
def test_put_get(self): hash_map = HashMap() for key in range(1, 21): value = key * 2 hash_map.put(key, value) self.assertEqual(hash_map.get(key), value)
class test_hashmap(unittest.TestCase): """ Test class for class Hashmap In all the quadratic probing tests unexpected errors can occur, for example if size of hashmap is small even one element can fill up a significant amount of size of the hashmap. Therefore I didn't use loop testing in quadratic probing it was causing random errors! """ def setUp(self): size = math.floor( random.random() * 30) + 30 # minimum size 15 to avoid coflicts with line 26 self._dict = HashMap(size, probing='quadratic', verbose=False) def test_hash_index(self): idx = self._dict.hash_index('divyansh') verify = 'divyansh'.__hash__() & ( self._dict.size - 1 ) # __hash__ returns different hashes for different python runs self.assertEqual(idx, verify) def test_sanity_check_key(self): self.assertRaises(ValueError, self._dict.sanity_check_key, 23) # passed any number to raise exception self.assertRaises(ValueError, self._dict.sanity_check_key, [2, 3, 4]) # passed a list to raise exception self.assertRaises(ValueError, self._dict.sanity_check_key, ('asd', 'asd')) # passed a tuple to raise exception def test_probe_linear(self): self._dict.probing = 'linear' num = self._dict.probe(5) self.assertEqual(num, 6) self._dict.ctr = 1 num = self._dict.probe(self._dict.size + 3) self.assertEqual(num, 4) def test_probe_quadratic(self): self._dict.probing = 'quadratic' self.assertEqual(self._dict.probe(5), 6) self.assertEqual(self._dict.probe(6), 10) self.assertEqual(self._dict.probe(1), 10) self._dict.reset() self.assertEqual(self._dict.probe(self._dict.size - 1), 0) self.assertEqual(self._dict.probe(self._dict.size - 1), 3) def test_set_quadratic(self): self.assertEqual(self._dict.set('animal', 'monkey'), True) self.assertEqual(self._dict.set('animal', 'lion'), True) self.assertRaises(ValueError, self._dict.set, 23, 'twenty_three') def test_set_linear(self): self._dict.probing = 'linear' self.assertEqual(self._dict.set('animal', 'monkey'), True) self.assertEqual(self._dict.set('animal', 'lion'), True) self.assertRaises(ValueError, self._dict.set, 23, 'twenty_three') self._dict.reset() for i in range(self._dict.size): self.assertEqual( self._dict.set('animal' + str(i), 'monkey' + str(i)), True) self.assertEqual(self._dict.load(), 1) self.assertEqual( self._dict.set('one_more_key_to_cause_overflow', 'monkey_n'), False) def test_get_quadratic(self): self.probing = 'quadratic' self.assertEqual(self._dict.set('animal' + str(3), 'monkey' + str(3)), True) self.assertEqual(self._dict.get('animal' + str(3)), 'monkey' + str(3)) self.assertRaises(KeyError, self._dict.get, 'bird') def test_get_linear(self): self._dict.probing = 'linear' for i in range(self._dict.size): self.assertEqual( self._dict.set('animal' + str(i), 'monkey' + str(i)), True) for i in reversed(range(self._dict.size)): self.assertEqual(self._dict.get('animal' + str(i)), 'monkey' + str(i)) self.assertRaises(KeyError, self._dict.get, 'bird') def test_delete_quadratic(self): self._dict.probing = 'quadratic' self._dict.set('animal', 'monkey') self._dict.delete('animal') self.assertRaises(KeyError, self._dict.get, 'animal') def test_delete_linear(self): self._dict.probing = 'linear' self._dict.set('animal', 'monkey') self._dict.delete('animal') for i in range(self._dict.size): self.assertEqual( self._dict.set('animal' + str(i), 'monkey' + str(i)), True) for i in reversed(range(self._dict.size)): self.assertEqual(self._dict.delete('animal' + str(i)), None) self.assertRaises(KeyError, self._dict.delete, 'animal' + str(i)) self.assertRaises(KeyError, self._dict.get, 'animal') def test_load_quadratic(self): self.probing = 'quadratic' itr = math.floor(random.random() * self._dict.size / 2 + 5) for i in range(itr): random_key = ''.join( random.choices(string.ascii_uppercase + string.digits, k=15)) self._dict.set(random_key, 'monkey' + str(i)) load_value = self._dict.load() self.assertLessEqual(load_value, 0.6) def test_load_linear(self): self.probing = 'linear' itr = math.floor(random.random() * self._dict.size + 5) for i in range(itr): random_key = ''.join( random.choices(string.ascii_uppercase + string.digits, k=15)) self._dict.set(random_key, 'monkey' + str(i)) load_value = self._dict.load() self.assertLessEqual(load_value, 1)