def test_collisions(): h = HashTable() h.add(25, "foo") h.add(125, "bar") assert len(h.data[25]) == 2 assert h.get(25) == "foo" assert h.get(125) == "bar"
class Scanner: def __init__(self, problem_file, tokens, separators): self.__problem_file = problem_file self.__tokens = tokens self.__separators = separators self.__pif = HashTable() self.__st = SymbolTable() def scan(self): line_count = 0 for line in self.__problem_file.read().splitlines(): line_count += 1 for token in self.tokenize(line): if token in self.__tokens: self.__pif.add(token, (-1, 1)) elif isinstance(token, Identifier) or isinstance( token, Constant): token_id = self.__st.add(token) self.__pif.add(token, token_id) else: print('Lexical error for token:', token, ', at line:', str(line_count)) return def tokenize(self, line): return line.split(str(self.__separators)) def get_pif(self): return self.__pif def get_st(self): return self.__st
class SymbolTable: def __init__(self): self.table = HashTable() self.checkingTable = {} def add(self, new_entry): entry = self.checkingTable.get(new_entry.get_key()) if entry is None: self.checkingTable[new_entry.get_key()] = new_entry.get_value() self.table.add(new_entry.get_key(), new_entry.get_value()) else: if isinstance(new_entry, Identifier): self.table.add(new_entry.get_key(), new_entry.get_value()) return new_entry.get_key() def get(self, key): return self.table.get(key) def get_table(self): return self.table.items() def __str__(self): return str(self.table.items()) def print_symbol_table(self): for key in self.table.items(): value = self.table.items()[key] print("{ ID:", value[0], ", Value:", value[1], "}")
def test_add_multiple(): ht = HashTable() ht.add('one', 1) ht.add('two', 2) ht.add('three', 3) assert ht.contains('one') == True assert ht.contains('two') == True assert ht.contains('three') == True
def form_parametrize_add(): """Forming parameters for testing function add""" dict_1 = {item: item ** 2 for item in range(100)} dict_2 = HashTable(100) result = [] for i in range(100): dict_2.add(str(i), i ** 2) result.append((dict_2[str(i)], dict_1.get(i))) return result
def test_add_method(): hash_table = HashTable() # add first key-value pair hash_table.add("Cat", "Frodo") # check if index that not 808 still has '0' in it assert hash_table._array[809] == 0 # check if index 808 not '0' anymore assert hash_table._array[808] != 0 assert hash_table._array[808].head.key == "Cat" assert hash_table._array[808].head.value == "Frodo" assert hash_table._array[808].head.next == None
class BETrainingModel: def __init__(self, model_path='default_model', beam_size=1): self.model_path, self.model_name = split_path(model_path) self.beam_size = beam_size self.perceptron = None self.label_hash = HashTable() def save(self): labels_file = self.create_file_with_extension('label') self.label_hash.save_file(labels_file) with open(self.create_file_with_extension(), 'w') as model_file: model_file.write(str(self.beam_size) + '\n') model_file.write(str(labels_file) + '\n') model_file.write( str(self.create_file_with_extension('weights')) + '\n') def setup_model(self, corpus_file): # index dependency label for label in get_label_conll(corpus_file): self.label_hash.add(label) n_class = len(self.label_hash) * 2 self.perceptron = MultitronParameters(n_class) self.save() def save_weight_file(self, iter): weights_file_path = self.create_file_with_extension('weights.' + iter) self.perceptron.dump_fin(file(weights_file_path, 'w')) def update_perceptron_counter(self): self.perceptron.tick() def create_file_with_extension(self, ext=''): return os.path.join(self.model_path, self.model_name + '.' + ext) def get_scores(self, features): return self.perceptron.get_scores(features) def update_paramaters(self, features, cls, value): self.perceptron.add(features, cls, value) @classmethod def load(cls, model_path): model_dir, model_file = split_path(model_path) with open(model_path, 'r') as f: beam_size = int(f.readline().strip()) label_hash_file = f.readline().strip() label_hash = load_hash_from_file(label_hash_file) weights_file_path = f.readline().strip() + ".FINAL" perceptron = MulticlassModel(weights_file_path) return cls(model_path, beam_size, perceptron, label_hash)
def hash_table_test(): # Create hash table h = HashTable() # Populate it for _ in range(100): h.add(random_element()) h.add(Element('topher', 1337)) # Print the table h.print() # Try a find print(h.find('topher').output())
def test_get(): one = HashTable() one.add('fond','enamored') one.add('wrath', 'anger') one.add('diligent', 'employed') one.add('outfit', 'garb') one.add('guide', 'usher') assert one.get('fond') == 'enamored'
def store_package_table(package_file): # packages with delivery addresses package_hash = HashTable() for item in package_to_list(package_file): # Delivery Status is initialized to In Hub current_location = 'At Hub' if 'Delayed' in item[7]: # findall would be bound by a constant so this line is O(1) match = re.findall(r'\d{1,2}:\d{2}\s\w{2}', item[7]) current_location = 'Arriving at ' + match[0] package_value = [current_location, 'Not On Truck', 'Not Delivered'] for index in range(1, 8): package_value.append(item[index]) # sets the package ID as a key and a list of delivery status, address, city, state, zip, deadline, and # notes as a value. package_hash.add(int(item[0]), package_value) return package_hash
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)
graph2 = Graph() graph3 = Graph() route1 = Route() route2 = Route() route3 = Route() # Reading in data from package file # Time Complexity: O(N) # Space Complexity: O(N) with open('WGUPS Package File.csv', mode='r', encoding='utf-8-sig') as packages: string = packages.readlines() for _ in range(40): aaa, bbb, ccc, ddd, eee, fff, ggg, hhh = string[_].split(sep=',', maxsplit=7) ccc = ccc + ', ' + ddd aaa = int(float(aaa)) package_object.add(aaa, Package(aaa, bbb, ccc, eee, fff, ggg, hhh)) # Create an array for inclusion in adjacency list from WGUPS Distance Table # with open('WGUPS Distance Table.csv', mode='r', encoding='utf-8-sig') as distances: string = distances.readlines() distances_list = [] temp_list = [] # Time Complexity: O(N^2) # Space Complexity: O(N) def get_missing_values(): start_index = 0 end_index = 1 for x_one in range(0, num_locations):
class TestLinkedList(unittest.TestCase): def setUp(self): self.ht = HashTable() self.ht.add(1, 'hello') self.ht.add(2, 'hi') self.ht.add(3, 'how') self.ht.add('foo', 'are') self.ht.add(5, 'foo') self.ht.add(36, 'bar') self.ht.add('a', 'baz') def test_add(self): self.assertEqual(self.ht[1], 'hello') self.assertEqual(self.ht[3], 'how') self.assertEqual(self.ht['foo'], 'are') self.assertEqual(self.ht['a'], 'baz') self.ht.add(1, 'Modified') self.assertEqual(self.ht[1], 'Modified') self.assertEqual(self.ht.getSize(), 7) self.assertEqual(self.ht.getCapacity(), 12) def test_remove(self): self.assertEqual(self.ht.remove(1), True) self.assertIsNone(self.ht[1]) self.assertEqual(self.ht.remove('ab'), False) def test_aux_methods(self): self.assertEqual(self.ht.getSize(), 7) self.assertEqual(self.ht.getCapacity(), 12) self.ht.add(55, 'foo') self.ht.add(1, 'bar') self.ht.add('random', 'baz') self.assertEqual(self.ht.getSize(), 9) self.assertEqual(self.ht.getCapacity(), 24)
class Graph: main_adj_list = HashTable(27) # Time Complexity: O(1) # Space Complexity: O(1) def __init__(self): self.node_id = 0 self.num_vertices = 0 self.is_first = True self.memo_dest_list = [] self.alt_dest_list = [] self.dest_list = [] self.path_list = [] self.memo = [] self.back_to_node0 = [] self.removal_list = [] self.min_element = [500, 500] self.main_path_sum = 0.0 self.node0_path_sum = 0.0 self.total_path_sum = 0.0 self.last_min_value = [] self.edges_list = HashTable() # Add vertices # Time Complexity: O(1) # Space Complexity: O(1) def add_vertex(self, node_id): new_node = Node(node_id) self.node_id = new_node.node_id # print(f'Get_node_id: {node_id}') self.dest_list.append(node_id) # self.show_destinations() self.num_vertices += 1 # Add edges # Time Complexity: O(1) # Space Complexity: O(1) def add_edge(self, src_node_id, dest_node_id, miles): new_edge = Edge(src_node_id, dest_node_id, miles) self.edges_list.add(src_node_id, new_edge) # Time Complexity: O(1) # Space Complexity: O(1) def show_destinations(self): return print(f'Destinations: {self.dest_list}') # Time Complexity: O(N) # Space Complexity: O(1) def find_shortest_path(self, source_id): source_id = int(source_id) if self.is_first: self.path_list.append([source_id, 0]) self.is_first = False find_list = list((self.main_adj_list.get(source_id))[1]) find_list = [float(i) for i in find_list] self.dest_list = [int(i) for i in self.dest_list] if len(self.memo_dest_list) == 0: self.memo_dest_list = self.dest_list # Make a copy of destinations for later else: self.dest_list = self.memo_dest_list if source_id == [self.dest_list[x] for x in range(len(self.dest_list))]: self.dest_list.remove(source_id) self.dest_list = set(self.dest_list) self.alt_dest_list = self.dest_list.copy() # Create copy of dest_list for alternative route direct_path_x = [] # Time Complexity: O(N^2) # Space Complexity: O(N) def iteration(list_a, remove_a=None): if remove_a is None: remove_a = [] else: remove_a = list(remove_a) # Time Complexity: O(N) # Space Complexity: O(1) if len(remove_a) != 0: for r in range(len(remove_a)): self.alt_dest_list.remove(remove_a[r]) x = 0 # Time Complexity: O(N^2) # Space Complexity: O(N) for each in list_a: for every_d in self.alt_dest_list: if each != 0.0: if every_d == x: direct_path_x.append(['{} -->'.format(source_id), x, find_list[x]]) if each < self.min_element[1]: self.min_element = [x, each] else: continue x += 1 return self.min_element last_key = -1 itt = [] # Time Complexity: O(N) # Space Complexity: O(N) while last_key not in self.dest_list: if len(self.removal_list) == len(self.dest_list): itt = self.last_min_value break itt = iteration(find_list, self.removal_list) self.last_min_value = itt last_key = itt[0] if itt[0] != 500: self.removal_list.append(itt[0]) find_list = list(self.main_adj_list.get(itt[0])[1]) if not itt: itt = list(self.last_min_value) if [13, 7.2] in self.path_list and len(self.path_list) != len(self.dest_list) + 4: # to accommodate the values manually deleted if itt[0] in self.dest_list: self.path_list.append(itt) self.dest_list.remove(itt[0]) self.dest_list = list(self.dest_list) self.min_element = [500, 500] self.main_path_sum += itt[1] return itt else: return elif [13, 7.2] not in self.path_list and len(self.path_list) != len(self.dest_list) + 1: if itt[0] in self.dest_list: self.path_list.append(itt) self.dest_list.remove(itt[0]) self.dest_list = list(self.dest_list) self.min_element = [500, 500] self.main_path_sum += itt[1] return itt else: return else: return itt # Time Complexity: O(N) # Space Complexity: O(1) def go_home(self, source_id): source_id = int(source_id) find_list = list((self.main_adj_list.get(source_id))[1]) find_list = [float(i) for i in find_list] min_value = [0, find_list[0]] self.path_list.append(min_value) self.node0_path_sum += min_value[1] return min_value # Time Complexity: O(1) # Space Complexity: O(1) def show_path(self): return self.path_list
def test_insertion(): h = HashTable() h.add(48, "teststring") assert h.get(48) == "teststring"
#!/usr/local/bin/python3 from hash_table import HashTable if __name__ == '__main__': ht = HashTable() print("Current number of elements: ", ht._n) print("Current table capacity: ", len(ht._table)) print("Adding (1, one) pair...") ht.add(1, "one") print("Adding (2, two) pair...") ht.add(2, "two") print("Adding (3, three) pair...") ht.add(3, "three") print("Current number of elements: ", ht._n) print("Does key 2 exists?") if ht.exists(2): print("yes") else: print("no") print("Get value of key 1: ", ht.get(1)) print("Get value of key 2: ", ht.get(2)) print("Get value of key 3: ", ht.get(3)) print("Removing element with key 2") ht.remove(2) print("Does key 2 exists?") if ht.exists(2): print("yes") else: print("no")
def test_get_key(): hashtable = HashTable() hashtable.add('reeses puffs', '9 out of 10 rating') actual = hashtable.get('reeses puffs') expected = '9 out of 10 rating' assert actual == expected
def my_hash_table(): hash_table = HashTable() # add first key-value pair on the index 808 hash_table.add("Cat", "Frodo") hash_table.add("Dog", "Sam") hash_table.add("goD", "Zeus") hash_table.add("ogD", "test test") hash_table.add("NewKey", "new value") hash_table.add(12, "int key") hash_table.add(0.57, "float key") return hash_table
def test_contains(): ht = HashTable() ht.add('four', 4) assert ht.contains('four') == True assert ht.contains('whale') == False
def test_replacement(): h = HashTable() h.add(12, "foo") h.add(12, "bar") assert h.get(12) == "bar"
def test_hash_table(): hash_table = HashTable(1024) hash_table.add("Guitar", "Gibson") hash_table.add("Bass", "Fender") hash_table.add("symbol", "Zildjan") hash_table.add("car", "tesla") hash_table.add("NewKey", "new value") hash_table.add(10, "int key") hash_table.add(0.5, "float key") return hash_table
def test_left_join_no_matches(): one = HashTable() one.add('pond','enamored') one.add('rath', 'anger') one.add('adiligent', 'employed') one.add('poutfit', 'garb') one.add('hangguide', 'usher') two = HashTable() two.add('fond', 'averse') two.add('wrath', 'delight') two.add('diligent', 'idle') two.add('guide', 'follow') two.add('flow', 'jam') assert left_join(one, two) == [['poutfit', 'garb', None], ['hangguide', 'usher', None], ['rath', 'anger', None], ['pond', 'enamored', None], ['adiligent', 'employed', None]]
def test_get(): ht = HashTable() ht.add('five', 5) assert ht.get('five') == 5 assert ht.get('tiger') == None
class HashTableTest(TestCase): def setUp(self) -> None: self.hash_table = HashTable() def test_attributes(self): self.assertEqual(4, len(self.hash_table.keys)) self.assertEqual(4, len(self.hash_table.values)) self.assertEqual(4, self.hash_table.capacity) def test_with_available_space(self): self.hash_table.add("Bobby", "5") self.assertEqual(1, self.hash_table.actual_length) self.assertEqual(4, self.hash_table.capacity) self.assertEqual("5", self.hash_table["Bobby"]) def test_without_available_space_increase_size(self): for number in range(1, self.hash_table.capacity + 1): self.hash_table.add(f"test_{number}", f"value_{number}") self.assertEqual(4, self.hash_table.actual_length) self.assertEqual(4, self.hash_table.capacity) self.hash_table.add("test_5", "value_5") self.assertEqual(5, self.hash_table.actual_length) self.assertEqual(8, self.hash_table.capacity) self.assertIn("test_5", self.hash_table.keys) def test_value_replaced_if_key_exist(self): self.hash_table.add("Bobby", "5") self.assertEqual("5", self.hash_table["Bobby"]) self.hash_table["Bobby"] = "6" self.assertEqual("6", self.hash_table["Bobby"]) def test_get_existing_key(self): self.hash_table.add("Bobby", "5") self.assertEqual("5", self.hash_table.get("Bobby")) def test_get_no_existing_key(self): self.hash_table.add("Bobby", "5") self.assertIsNone(self.hash_table.get("B")) def test_representation(self): self.hash_table.add("Bobby", "5") self.assertEqual("{Bobby: 5}", str(self.hash_table))
def test_add_hash_table(): hashtable = HashTable() hashtable.add('spam', "fried egg") actual = hashtable.get('spam') expected = 'fried egg' assert actual == expected
def test_add_key(): ht = HashTable() ht.add('keyTest', 1) assert ht.contains('keyTest') == True
def test_get_value_from_key(): hashtable = HashTable() hashtable.add('cheerios', '1 out of 10 rating') hashtable.add('ct crunch', '8 out of 10 rating') assert hashtable.get('ct crunch') == '8 out of 10 rating' assert hashtable.get('cheerios') == '1 out of 10 rating'
words[i] = "<<" del words[i+1] if words[i] == ">" and words[i+1] == ">": words[i] = ">>" del words[i+1] if words[i] == "-" and isIntConstant(words[i+1]): words[i] = "-" + words[i+1] del words[i+1] i += 1 for word in words: if word in reserved_words: pif[word] = -1 elif isIntConstant(word): position = st.add(word) pif[word] = position elif isStringConstant(word): position = st.add(word) pif[word] = position elif isCharConstant(word): position = st.add(word) pif[word] = position elif isIdentifier(word): position=st.add(word) pif[word] = position else: raise Exception("Lexical error. Invalid " + word + " on line "+ str(line_nr)) line = file.readline() line_nr += 1