def test_hasher(): ht = HashTable() a = ht.hash("alice") b = ht.hash("elica") c = ht.hash("Alice") assert a == b assert a != c
def main(): testHashToIndex() print("Starting with empty hash table") hash = HashTable() hash.put("A key", "a value") assert hash.get("A key") == "a value" assert hash.get("A key") != "another value"
def loadHash(lista): if not lista is None: MyHash = HashTable() for item in lista: MyHash.insert(item, item) return MyHash return None
def insertarTablaHash(arregloLleno: List, tablaHash : HashTable): ''' Para insertar en la tabla hash los usuarios registrados :param arregloLleno: arreglo de 2-tuplas compuesto por el nombre de usuario y el arreglo de volumen :param tablaHash: tabla hash donde se guardarn todos los nombres de los usuarios y el arreglo de volumen ''' for i in arregloLleno: tablaHash.set(i[0],i[1])
def console(): hash_table = HashTable() while True: op = input(prompts['operations']) if op == '1': word = input(prompts['word']) hash_table.add(word) print(hash_table) elif op == '4': return
def _getLocations( self ): table = HashTable(10) # Add locations to hash table with open( 'data/locations.csv' ) as file: locationData = csv.reader( file, delimiter=',' ) # Iterate through locations # Time Complexity: O(n) for row in locationData: location = Location( row[0], row[1], row[2] ) # Add location to hash table of locations table.put( int( location.id ), location ) return table
def generation_mode(file_in, num, seed, file_del=None): words = synthetic.words(file_in, num, seed) size = input("How many lists should be in the hashmap?: ") try: size = int(size) except ValueError as e: print("ERROR: Invalid value was passed to the program.\n", e) return -1 hash_table = HashTable(size) begin = time.perf_counter() hash_table.add_all(words) end = time.perf_counter() print("Adding time [s]: {:.6f}".format(end - begin)) begin = time.perf_counter() for word in words: hash_table.find(word) end = time.perf_counter() print("Enumerating time [s]: {:.6f}".format(end - begin)) if file_del is not None: words = synthetic.read_file(file_del) begin = time.perf_counter() for word in words: hash_table.delete_all(word) end = time.perf_counter() print("Deleting time [s]: {:.6f}".format(end - begin))
class Node(object): def __init__(self, location): self.edges = HashTable(10) self.location = location #Time Complexity: O(n) where n is the number of edges def addEdge(self, edge): self.edges.put(int(edge.id), edge) #Time Complexity: O(n) where n is the number of edges def findEdge(self, id): return self.edges.get(id) #Time Complexity: O(n) where n is the number of edges def getDistance(self, location): return self.edges.get(location.id).weight
def test_hash_table_constructor_creates_empty_hash_table(): """Test that HashTable constructor creates an empty hash table.""" from hash import additive_hash, HashTable t = HashTable(10, additive_hash) assert len(t.buckets) == 10 assert t.hash_func is additive_hash assert not all(t.buckets)
def __init__(self): #connect to permanent storage self.create_flag = False self.delimiter = '|' self.storage = "permanent_data.txt" self.database = HashTable(5479) #call function to read existing data into hash table self._import_data()
def _getPackages( self ): packages = HashTable(10) with open('data/packageFile.csv') as file: packageData = csv.reader( file, delimiter = ',' ) for row in packageData: package = Package( row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7] ) package.setLocation( self.getLocationByAddress( row[1] ) ) packages.put( package.id, package ) return packages
def gen_step_mode(file_in, num, seed, file_del=None): size = input("How many lists should be in the hashmap?: ") step_val = input( "Specify the step value (number of words generated additionally): ") try: size = int(size) step_val = int(step_val) except ValueError as e: print("ERROR: Invalid value was passed to the program.\n", e) return -1 words_num = 0 results = [] while True: words_num += step_val if words_num > num: break print(words_num, " words") results.append(words_num) words = synthetic.words(file_in, words_num, seed) hash_table = HashTable(size) begin = time.perf_counter() hash_table.add_all(words) end = time.perf_counter() print("Adding time [s]: {:.6f}".format(end - begin)) results.append(end - begin) begin = time.perf_counter() for word in words: hash_table.find(word) end = time.perf_counter() print("Enumerating time [s]: {:.6f}".format(end - begin)) results.append(end - begin) if file_del is not None: words = synthetic.read_file(file_del) begin = time.perf_counter() for word in words: hash_table.delete_first(word) end = time.perf_counter() print("Deleting time [s]: {:.6f}".format(end - begin)) results.append(end - begin) analyse_data(results, num, size)
class Graph(object): def __init__(self): self.nodes = HashTable(10) # Add a vertex to the graph # Time Complexity: O(n) def addNode(self, location): self.nodes.put(int(location.id), Node(location)) # Add edge between two nodes bidirectionally # Time Complexity: O(n) def addWeightedEdge(self, origin, terminus, weight): originEdge = Edge(origin, weight) terminusEdge = Edge(terminus, weight) self.nodes.get(origin.id).addEdge(terminusEdge) self.nodes.get(terminus.id).addEdge(originEdge) # Get id of a vertex at a location # Time Complexity: O(n) def getNode(self, location): return self.nodes.get(location.id) # Get first node returned by location name: O(n) def getNodeByAddress(self, address): for node in self.nodes.getAll(): if (node.location.address == address): return node # Get distance between two lcoations def getDistanceBetween(self, origin, terminus): return self.nodes.get(origin.id).getDistance(terminus) # Get nearest neighbor of a location # Returns the closest location to the origin # Time Complexity: O(n * m) def getNearestNeighbor(self, origin, group): resultEdges = [] originNode = self.getNodeByAddress(origin.address) originEdges = originNode.edges.getAll() for location in group: for edge in originEdges: if location == edge.location: resultEdges.append(edge) nearestNeighbor = min(resultEdges, key=lambda x: x.weight) return nearestNeighbor.location
class test_hash(unittest.TestCase): def setUp(self): self.hash = HashTable(11) def test_put(self): self.hash.put("Lindsey Raymond", "9786217554") self.assertEqual(self.hash.keys[3], "Lindsey Raymond") self.assertEqual(self.hash.data[3], "9786217554") def test_get(self): self.assertEqual(self.hash.get("Lindsey Raymond"), "9786217554") def test_size(self): self.assertEqual(self.hash.length, 11) def test_get(self): self.hash["James Hayward"] = "123456789" self.hash.put("Lindsey Raymond", "9786217554") self.assertEqual(self.hash["Lindsey Raymond"], self.hash.get("Lindsey Raymond")) self.assertEqual(self.hash["James Hayward"], "123456789")
def words_ready_mode(file_in, file_del=None): words = synthetic.read_file(file_in) print(words) size = input("How many lists should be in the hashmap?: ") try: size = int(size) except ValueError as e: print("ERROR: Invalid value was passed to the program.\n", e) return -1 hash_table = HashTable(size) hash_table.add_all(words) for arr in hash_table.array: print(arr) if file_del is not None: words = synthetic.read_file(file_del) for word in words: hash_table.delete_all(word) for arr in hash_table.array: print(arr)
class Phonebook: def __init__(self): #connect to permanent storage self.create_flag = False self.delimiter = '|' self.storage = "permanent_data.txt" self.database = HashTable(5479) #call function to read existing data into hash table self._import_data() def _read_lines(self): with open(self.storage, 'r') as old_data: for row in old_data: if not row.startswith("#"): yield row def _import_data(self): for row in self._read_lines(): if row.startswith("~"): self.create() else: name = row.split(self.delimiter)[0] number = row.split(self.delimiter)[-1] self.database[name] = number def add(self, name, number): #print(self.database.hashkeys) if name not in set(self.database.hashkeys): self.database[name] = number else: raise KeyError("Value already exists") def remove(self, name): self.database.put(name, None) self.database.hashkeys[self.database.hashkeys.index(name)] = None def change(self, name, number): if name in set(self.database.hashkeys): self.database[name] = number else: raise KeyError("Value does not exist") def lookup(self, name): try: return self.database[name] except: raise KeyError("Value does not exist") def reverse_lookup(self, number): #Note that this will be slow try: location = self.database.data.index(number) return self.database.hashkeys[location] except: raise LookupError("Value does not exist") def create(self): self.create_flag = True def save(self): with open(self.storage, 'w') as txt_file: txt_file.write("#permanent storage file\n") if self.create_flag: txt_file.write("~CREATED\n") for name in self.database.keys: if name != None: txt_file.write(name+"|"+self.database[name]+"\n") def check_input_errors(self, args): if len(args) == 1: raise RuntimeError("Need more input") def parse_arguments(self, args): self.check_input_errors(args) if self.create_flag: if args[1] == "add": self.add(*args[2:4]) else: result = getattr(self, args[1])(args[2]) else: if args[1] == 'create': self.create() else: raise RuntimeError("Phonebook does not exist") self.save() return result
def setUp(self): self.hash = HashTable(11)
def dict_hash(): dict_hash = HashTable(1024) dictionary = open("/usr/share/dict/words", 'r') for word in dictionary: dict_hash.set(word.rstrip(), 1) return dict_hash
def test_hash_fill_table(read_test_lexicon): ht = HashTable() for i in read_test_lexicon: ht.set(i) for i in read_test_lexicon: assert ht.get(i) == i
class TestHashTable(unittest.TestCase): def setUp(self): self.ht = HashTable() def test_hash(self): self.assertEqual(self.ht.hash("Maximus"), self.ht.hash("Maximus")) self.assertTrue(self.ht.hash("Maximus") < self.ht.capacity) def test_insert(self): self.ht.insert("key", "value") self.assertEqual(self.ht.size, 1) self.assertEqual(self.ht.buckets[self.ht.hash("key")].value, "value") def test_find(self): obj = "Maximus" self.ht.insert("Intel", obj) self.assertEqual(obj, self.ht.find("Intel")) obj = ["Hello", "world"] self.ht.insert("hobby", obj) self.assertEqual(obj, self.ht.find("hobby")) def test_remove(self): obj = "19" self.ht.insert("age", obj) self.assertEqual(1, self.ht.size) self.assertEqual(obj, self.ht.remove("age")) self.assertEqual(0, self.ht.size)
def test_get_returns_value_of_key_provided(): """Test that get function returns the value of key provided.""" from hash import HashTable, additive_hash t = HashTable(10, additive_hash) t.set('word', 444) assert t.get('word')
def test_get_raises_error_if_key_not_not_in_table(): """Test that keyerror raised if key not in table.""" from hash import HashTable, additive_hash t = HashTable(10, additive_hash) with pytest.raises(KeyError): t.get('key')
def test_set_raises_error_if_key_not_string(): """Test that type error raised if key not string in set.""" from hash import HashTable, additive_hash t = HashTable(10, additive_hash) with pytest.raises(TypeError): t.set(12, 44)
def test_set_places_key_value_pairs_in_hash_table(): """Test that set function places key value pairs in hash table correctly.""" from hash import HashTable, additive_hash t = HashTable(10, additive_hash) t.set('word', 444) assert t.buckets[4][0] == ['word', 444]
def test_hash_initialized_with_oat(): """Test if hash table can be initialized using oat hashing function.""" from hash import HashTable cust_hash = HashTable(hash_type='oat') cust_hash.hash_type == 'oat'
def table1key(): """Table with just 1 key/pair.""" t = HashTable() t.set_key('apple', 'chapel') return t
def table6_add(): """Initialize table with 6 buckets.""" t = HashTable() return t
class TestHashTable(unittest.TestCase): def setUp(self): self.ht = HashTable() def test_hash(self): self.assertEqual(self.ht.hash("hello"), self.ht.hash("hello")) self.assertTrue(self.ht.hash("hello") < self.ht.capacity) def test_insert(self): self.assertEqual(self.ht.size, 0) self.ht.insert("test_key", "test_value") self.assertEqual(self.ht.size, 1) self.assertEqual( self.ht.buckets[self.ht.hash("test_key")].value, "test_value") def test_find(self): self.assertEqual(self.ht.size, 0) obj = "hello" self.ht.insert("key1", obj) self.assertEqual(obj, self.ht.find("key1")) obj = ["this", "is", "a", "list"] self.ht.insert("key2", obj) self.assertEqual(obj, self.ht.find("key2")) def test_remove(self): self.assertEqual(self.ht.size, 0) obj = "test object" self.ht.insert("key1", obj) self.assertEqual(1, self.ht.size) self.assertEqual(obj, self.ht.remove("key1")) self.assertEqual(0, self.ht.size) self.assertEqual(None, self.ht.remove("some random key")) def test_capacity(self): # Test all public methods in one run at a large capacity for i in range(0, 1000): self.assertEqual(i, self.ht.size) self.ht.insert("key" + str(i), "value") self.assertEqual(self.ht.size, 1000) for i in range(0, 1000): self.assertEqual(1000-i, self.ht.size) self.assertEqual(self.ht.find("key" + str(i)), self.ht.remove("key" + str(i))) def test_issue2(self): self.assertEqual(self.ht.size, 0) self.ht.insert('A', 5) self.assertEqual(self.ht.size, 1) self.ht.insert('B', 10) self.assertEqual(self.ht.size, 2) self.ht.insert('Ball', 'hello') self.assertEqual(self.ht.size, 3) self.assertEqual(5, self.ht.remove('A')) self.assertEqual(self.ht.size, 2) self.assertEqual(None, self.ht.remove('A')) self.assertEqual(self.ht.size, 2) self.assertEqual(None, self.ht.remove('A')) self.assertEqual(self.ht.size, 2)
def test_get_non_string_key_raises_error(): """Test taht get with a non string key raises error.""" from hash import HashTable, additive_hash t = HashTable(10, additive_hash) with pytest.raises(TypeError): t.get(22)
def setUp(self): self.ht = HashTable()
def test_bad_hash_type_raises_error(): """Test if ValueError raised if function other than additive or oat is passed.""" from hash import HashTable with pytest.raises(NameError): HashTable(hash_type='something')
def table6_elf(): """Initialize table with 6 buckets.""" t = HashTable(hash_type='elf') return t
def test_hash_table_uses_additive_hash_function(): """Test that hash table hashes keys with function provided.""" from hash import additive_hash, HashTable t = HashTable(10, additive_hash) assert t._hash('one') == additive_hash('one')
def adt6_no_dups(): """Full hash table with only one item in each bucket.""" t = HashTable() t.set_key('aaaaaa', 'bettie') t.set_key('a', 'bettie') t.set_key('apple', 'bob') t.set_key('potato', 'fred') t.set_key('spinach', 'james') t.set_key('sweet potato', 'jenny') return t
def test_hash_table_uses_horner_hash_function(): """Test that hash table hashes keys with function provided.""" from hash import horner_hash, HashTable t = HashTable(10, horner_hash) assert t._hash('two') == horner_hash('two')