def test_set(self): h = HashTable(30) h.set('puppy', 'cute') actual = h.hlist[4] expected = [('puppy', 'cute')] assert actual == expected assert h.hlist[0] == []
def test_hash(): """Test hash function.""" from hash_table import HashTable new_hash = HashTable(100) hashed = new_hash._hash('string') assert hashed < len(new_hash.table) assert isinstance(hashed, int)
def test_set_empty(): """Test set on empty table.""" string = "test" ht = HashTable() check = ht._hashing(string, ht._size) ht.set("test", "test") assert ht._table[check] == [(check, "test")]
def test_word_file(): ht = HashTable() for word in words: ht.set(word, word) assert ht.get(words[654]) == words[654] assert ht.get(words[3541]) == words[3541] assert ht.get(words[6541]) == words[6541]
def build_histogram(tokens): histogram = HashTable() for token in tokens: if not histogram.contains(token): histogram[token] = 0 histogram[token] += 1 return histogram
def test_collision(): """Test hash puts multiple buckets in one slot where needed.""" small_table = HashTable(2) small_table.set("a", "hello") small_table.set("c", "world") assert ("a", "hello") in small_table._table[1] assert ("c", "world") in small_table._table[1] assert small_table._table[0] == []
def test_set(): """Test set function.""" from hash_table import HashTable new_hash = HashTable(1) new_hash.set('chicken', 'robot') assert new_hash.table[0][0][0] == 'chicken' assert new_hash.table[0][0][1] == 'robot' assert new_hash.table[0][0] == ('chicken', 'robot')
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 ht_ant_one(): """Hash table of words and their antonyms.""" ht = HashTable(10) ht.set('fond', 'averse') ht.set('wrath', 'delight') ht.set('diligent', 'idle') ht.set('outfit', 'follow') ht.set('guide', 'jam') return ht
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 load_package_data(): with open(packages_data_path, 'r') as packages_data_file: package_data_list = list(csv.reader(packages_data_file, delimiter=',')) package_hash_table = HashTable(len(package_data_list)) for package_data_row in package_data_list: package = Package( package_data_row ) package_hash_table.insert(package) return package_hash_table
def ht_syn_one(): """Hash table of words and their synonyms.""" ht = HashTable(10) # import pdb; pdb.set_trace() ht.set('fond', 'enamored') ht.set('wrath', 'anger') ht.set('diligent', 'employed') ht.set('outfit', 'garb') ht.set('guide', 'usher') return ht
def test_hash_on_word_list(): """Test that hash works on a giant list of words.""" from hash_table import HashTable import io new_hash = HashTable(500) file = io.open('/usr/share/dict/words') for i in range(250000): key = value = file.readline() new_hash.set(key, value) assert new_hash.get(key) == value
def test_values(self): """ A HashTable can produce a list of its values. """ h = HashTable() h['foo'] = 'bar' h['baz'] = 'qux' values = h.values() values.sort() self.assertEqual(['bar', 'qux'], values)
def test_hash_table_has_returns_the_same_index_whenever_called(self): ht = HashTable(10) first = ht.hash("name") second = ht.hash("name") self.assertTrue(first != None) self.assertTrue(second != None) self.assertTrue(isinstance(first, int)) self.assertTrue(isinstance(second, int)) self.assertEqual(first, second)
def test_keys(self): """ A HashTable can produce a list of its keys. """ h = HashTable() h['foo'] = 'bar' h['baz'] = 'qux' keys = h.keys() keys.sort() self.assertEqual(['baz', 'foo'], keys)
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_many(self): words = [line.strip() for line in open('/usr/share/dict/words')] words = words[:300] len_words = len(words) h = HashTable(len_words) for word in words: h.set(word, word) for l in h.hlist: print len(l) for word in words: assert h.get(word) == word
def setUp(self) -> None: self.H = HashTable() self.H[54] = "cat" self.H[26] = "dog" self.H[93] = "lion" self.H[17] = "tiger" self.H[77] = "bird" self.H[31] = "cow" self.H[44] = "goat" self.H[55] = "pig" self.H[20] = "chicken"
def repeated_word(lengthy_string): """Return the first repeated word of an lengthy input string.""" lengthy_string = lengthy_string.lower() lengthy_list = lengthy_string.split(' ') ht = HashTable(len(lengthy_list)) for word in lengthy_list: if ht.get(word): return word else: ht.set(word, word) return False
def __init__(self, circuit, previous, name: str, complete: bool, men_stats, women_stats, men_scoreboard, women_scoreboard): self.circuit = circuit self.previous = previous self.name = name self.complete = complete self.men_stats = men_stats self.women_stats = women_stats self.men_scoreboard = men_scoreboard self.women_scoreboard = women_scoreboard self.tournaments = HashTable() # <tournament name, tournament>
def test_get_conflict(self): h = HashTable(30) h.set('hi', 'HI') h.set('w', 'W') assert h.hash('w') == h.hash('hi') actual1 = h.get('hi') expected1 = 'HI' assert actual1 == expected1 actual2 = h.get('w') expected2 = 'W' assert actual2 == expected2
def main(): # Create hash table for packages package_hash_table = HashTable() # Create 40 packages and assign the address IDs # using the CSV data file all_packages = [] with open('package_data.csv') as data: package_data = csv.reader(data, delimiter=',') for row in package_data: package = Package(row[0], None, row[1], row[2], row[3], row[4], row[5], row[6], row[7], 'At hub') all_packages.append(package) # Add packages to hash table for package in all_packages: package_hash_table.insert(package.id_num, package) # Presort packages for each truck all_packages = PackageSorting.sort_packages(all_packages) # Create 3 load lists based on package priorities, possibly in a different class first_load = all_packages[0] second_load = all_packages[1] third_load = all_packages[2] # Run these lists through the sorting algorithm to compute the most efficient delivery order first_load = EfficiencyAlgorithm.organize_route(first_load) second_load = EfficiencyAlgorithm.organize_route(second_load) third_load = EfficiencyAlgorithm.organize_route(third_load) # Create and load 3 trucks first_truck = Truck(first_load) second_truck = Truck(second_load) third_truck = Truck(third_load) # Send the two drivers to begin deliveries at set times first_truck.begin_delivery('08:00 AM') second_truck.begin_delivery('09:05 AM') # Take address change for package #9 into account if first_truck.current_time >= '10:20 AM': for queue_item in third_load.queue: if 'Wrong address' in queue_item.item.notes: queue_item.item.address_id = 19 queue_item.item.address = '410 S State St' queue_item.item.zip_code = '84111' # Because there are only two drivers, wait until the # first returns before sending out the third one if first_truck.current_loc == 0: if first_truck.current_time <= '10:20:AM': # Take address change into account if not already done for queue_item in third_load.queue: if 'Wrong address' in queue_item.item.notes: queue_item.item.address_id = 19 queue_item.item.address = '410 S State St' queue_item.item.zip_code = '84111' third_truck.begin_delivery('10:20 AM') else: third_truck.begin_delivery(first_truck.current_time) # Create menu for input here to check things user_interface(package_hash_table, first_truck, second_truck, third_truck)
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 camouflage(clothes): wearing = HashTable(len(clothes)) for i in clothes: wearing.insert(i[1], i[0]) camo = 1 viewed_keys = [] for j in range(len(clothes)): if clothes[j][1] not in viewed_keys: camo *= (wearing.get_linked_list_for_key(clothes[j][1]).len() + 1) viewed_keys.append(clothes[j][1]) return camo - 1
def build_histogram_with_file(filename): word_dict = HashTable() list_word = [] with open(filename, 'r') as a_file: for a_line in a_file: words = re.findall(r"[a-zA-Z]+", a_line) for word in words: list_word.append(word) if not word_dict.contains(word): word_dict[word] = 0 word_dict[word] += 1 return word_dict, list_word
def test_find(self): """ Проверка поиска элемента по значению:""" self.h_table = HashTable(4, 3) self.h_table.put("AA") self.h_table.put("Bc") self.h_table.put("dE") self.h_table.put("eD") self.assertEqual(self.h_table.seek_slot("DD"), None) self.assertEqual(self.h_table.find("dE"), 0) self.assertEqual(self.h_table.find("eD"), 3) self.assertEqual(self.h_table.find("DD"), None)
def repeated_word(string): """Return first repeated word.""" try: all_words = string.lower().split(' ') except TypeError: raise TypeError ht = HT() for each in all_words: found = ht.get(each) if found: return each ht.set(each, each)
def test_table_collision(): "Tests the collision" obj = HashTable(size=1000) random_keys = [] for i in range(2000): random_key = ''.join(random.sample(string.ascii_lowercase, 10)) random_keys.append(random_key) obj.set(random_key, i) for i, random_key in enumerate(random_keys): assert obj.get(random_key) == i
def main(): H = HashTable() a = input("Enter your word:\n") filename = "ispell.dict" with suppress_stdout(): file = open(filename,"r") lines = [line.rstrip('\n') for line in file] for line in lines: H.inserthash(str(line)) file.close() print(H.searchhash(str(a)))
def __init__(self, truck_count=3, opening_time="08:00 AM"): print("Welcome to Hub Management Center") self.current_time = opening_time self.truck_count = truck_count self.trucks = [] self.add_truck(truck_count) self.center = Location("Western Governors University", "4001 South 700 E", 84107, "HUB") self.destinations = distance_table.DistanceTable() self.database = HashTable() self.load_locations() self.load_packages()
def test_naive_hash_causes_many_collisions(): """Tests if naive hash causes multiple collisions.""" from hash_table import HashTable hash_table = HashTable(hash_function='naive') equal = True while equal: sample_words = random.sample(list_words, 50) for word in sample_words: hash_table.set(word, word) hash_table_words = [hash_table.get(word) for word in sample_words] equal = hash_table_words == sample_words assert not equal
def __init__(self, player, wins=0, losses=0, points=0, scores=HashTable(), season_stats=HashTable()): self.player = player self.wins = wins self.losses = losses self.points = points self.scores = scores.clone() # <score, count> self.season_stats = season_stats.clone() # <season name, season stats>
class HashTest(TestCase): def setUp(self): self.test1 = HashTable(10) def test_type(self): self.assertIsInstance(self.test1, HashTable) def test_add(self): self.assertEqual(self.test1.insert("key", "var"), None) def test_search(self): self.test1.insert("key", "val") self.assertEqual(self.test1.search("key"), "val")
def uneven_table(): """Antonym table without all matches.""" table = HashTable() table.set('fond', 'averse') table.set('wrath', 'delight') table.set('flow', 'jam') return table
def repeated_word(string): """Takes a string as an argument. Returns the first word to be repeated.""" if type(string) is not str: raise TypeError('Please input a string.') words = string.split(' ') table = HashTable() for word in words: if table.get(word): return word table.set(word, word) raise KeyError('There are no duplicate words!')
def even_table_one(): """Synonyms hash table.""" table = HashTable() table.set('fond', 'enamored') table.set('wrath', 'anger') table.set('diligent', 'employed') return table
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 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"
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 count_tokens(tokenized_array): histogram = HashTable() for word in tokenized_array: searched_word_data = histogram.search(word) if searched_word_data is not None: histogram.set_value(word, searched_word_data[1] + 1) else: histogram.set_value(word, 1) return histogram
class TestHashTable(unittest.TestCase): def setUp(self): self.hash_table = HashTable(13) def test_init(self): bucket_size = len(self.hash_table.buckets) self.assertEqual(13, bucket_size) self.assertEqual(bucket_size, self.hash_table.bucket_count) self.assertEqual(0, self.hash_table.item_count) def test_set_value_for_key(self): self.hash_table["key"] = "Bob" self.assertEqual(1, self.hash_table.item_count) self.assertEqual("Bob", self.hash_table["key"]) self.hash_table["key"] = "Max" self.assertEqual("Max", self.hash_table["key"]) def test_get_value_for_key(self): self.hash_table["Bob"] = "male" self.hash_table["Bob"] = "alpha male" self.hash_table["Alexa"] = "female" self.assertNotEqual("male", self.hash_table["Bob"]) self.assertEqual("alpha male", self.hash_table["Bob"]) def test_remove_key(self): self.hash_table["Bob"] = "male" self.assertEqual("male", self.hash_table["Bob"]) self.assertEqual(1, self.hash_table.item_count) del self.hash_table["Bob"] self.assertEqual(0, self.hash_table.item_count) self.assertIsNone(self.hash_table["Bob"]) def test_contains(self): self.hash_table["Bob"] = "male" self.hash_table["Alex"] = "male" self.assertTrue("Bob" in self.hash_table) self.assertTrue("Alex" in self.hash_table) self.assertFalse("Chris" in self.hash_table) # test helper methods def test_get_bucket_index_for_key(self): index = self.hash_table._get_bucket_index_for_key("key") self.assertTrue(index < self.hash_table.bucket_count) self.assertTrue(isinstance(index, int))
def test_non_string(): ht = HashTable() with pytest.raises(TypeError): ht.set(13, 13)
def setUp(self): self.hash_table = HashTable(13)
def test_duplicate_hash_val(): ht = HashTable() ht.set('bob', 'bob') ht.set('obb', 'obb') assert ht.get('bob') == 'bob' assert ht.get('obb') == 'obb'
def test_multiple_tables(): ht1 = HashTable() ht2 = HashTable() ht1.set('coffee', 'coffee') ht1.set('eggs', 'eggs') ht2.set('bacon', 'bacon') with pytest.raises(KeyError): ht1.get('bacon') with pytest.raises(KeyError): ht2.get('coffee')
def test_hash(self): h = HashTable(30) actual = h.hash('puppy') expected = 4 assert actual == expected
def test_big_table(word_list): table = HashTable(4096) [table.set(word, word) for word in word_list] assert [table.get(word) == word for word in word_list] for word in word_list: print "expected: {}, seen: {}".format(word, table.get(word))
def test_key_is_string(self): h = HashTable(100) with self.assertRaises(TypeError) as context: h.set(1, 1) self.assertEqual(context.exception.message, u"key must be a string.")
def test_get(self): h = HashTable(30) h.set('puppy', 'cute') actual = h.get('puppy') expected = 'cute' assert actual == expected
def test_get(): """Test get method.""" hT = HashTable() hT.set("test", "test") assert hT.get("test") == "test"
def test_non_item(): ht = HashTable() ht.set('coffee', 'coffee') with pytest.raises(KeyError): ht.get('milk')
def test_end_to_end(self): hash_table = HashTable(10) print("Test: get on an empty hash table index") assert_equal(hash_table.get(0), None) print("Test: set on an empty hash table index") hash_table.set(0, 'foo') assert_equal(hash_table.get(0), 'foo') hash_table.set(1, 'bar') assert_equal(hash_table.get(1), 'bar') print("Test: set on a non empty hash table index") hash_table.set(10, 'foo2') assert_equal(hash_table.get(0), 'foo') assert_equal(hash_table.get(10), 'foo2') print("Test: set on a key that already exists") hash_table.set(10, 'foo3') assert_equal(hash_table.get(0), 'foo') assert_equal(hash_table.get(10), 'foo3') print("Test: remove on a key that already exists") hash_table.remove(10) assert_equal(hash_table.get(0), 'foo') assert_equal(hash_table.get(10), None) print("Test: remove on a key that doesn't exist") hash_table.remove(-1) print('Success: test_end_to_end')
from hash_table import HashTable terminator = False 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
def words_table(): from hash_table import HashTable big_table = HashTable(50) for word in get_words(): big_table.set(str(word), str(word)) return big_table
def words_table(request): """Big set of sample values.""" big_table = HashTable(1024) for word in get_words(): big_table.set(word, word) return big_table
def test_hash(): ht = HashTable() ht.set('coffee', 'coffee') assert ht.get('coffee') == 'coffee'