Ejemplo n.º 1
0
 def final_test(self):
     map = HashMap()
     map[1] = 100
     map[5] = 500
     map[20] = 5
     map["Hello"] = "Goodbye"
     assert (map.exists("Hello"))
     assert (map["Hello"]) == "Goodbye"
     map.delete("Hello")
     assert (map["Hello"]) == None
Ejemplo n.º 2
0
class LRUCache:
    def __init__(self, cache_size):
        self.map = HashMap()
        self.store = LinkedList()
        self.cache_size = cache_size

    def count(self):
        return len(self.map)

    def __getitem__(self, key):
        if self.map[key]:
            node = self.map[key]
            self.update_node(
                node
            )  # Because this is now the most recently seen object. i.e. keep it in cache
            return node.val
        return False

    def __str__(self):
        return 'Map: ' + str(self.map) + '\n' + 'Store: ' + str(self.store)

    def __setitem__(self, key, val):
        if key in self.map:
            self.map[key].val = val
            self.update_node(self.map[key])
        else:
            new_node = self.store.append(key, val)
            self.map[key] = new_node
        if self.count() > self.cache_size:
            self.eject()
        return val

    def update_node(self, node):
        node.remove()
        self.store.append(node.key, node.val)

    def eject(self):
        rm_node = self.store.first()
        rm_node.remove()
        self.map.delete(rm_node.key)
Ejemplo n.º 3
0
def test_hash_map():
    hash_map = HashMap(2)

    # Test HashMap get and put
    key = "abcde"
    value = "ramiz"
    hash_map.put(key, value)
    output = hash_map.get(key)
    assert_(value, output)

    # Test size
    assert_(1, hash_map.size())

    # delete
    hash_map.delete("abcde")
    assert_(0, hash_map.size())

    # Test Rehash
    hash_map.put("mine", "mine")
    # this should trigger rehashing
    hash_map.put("hi", "hi")
    assert_(2, hash_map.size())
    print("All Tests Passed!")
Ejemplo n.º 4
0
    def test_delete(self):
        hash = HashMap()
        hash[1] = 100
        hash[2] = 200
        hash[3.1] = 64
        assert (hash[1]) == 100
        assert (hash[2]) == 200
        assert (hash[3.1]) == 64
        assert (hash.data_count) == 3
        hash.delete(2)
        hash.delete(3.1)
        assert (hash[2]) == None
        assert (hash[3.1]) == None
        assert (hash.data_count) == 1

        # Deleting key not in hash should not decrement data count
        hash.delete(555)
        assert (hash.data_count) == 1
class HashMapTests(unittest.TestCase, DictTestCases):
    def setUp(self):
        self.uut = HashMap()

    def mock_hashes_to(self, index=0):
        class Mock(object):
            def __hash__(self):
                return index

            def __str__(self):
                return "mock(%s)" % index

            __repr__ = __str__

        return Mock()

    def test_initial_current_capacity_is_16(self):
        self.assertEqual(16, self.uut.capacity())

    def test_initial_doubling_size_is_12(self):
        self.assertEqual(12, self.uut.doubling_size())

    def test_when_inialized_with_one_half_then_doubling_size_is_8(self):
        uut = HashMap(0.5)
        self.assertEqual(8, uut.doubling_size())

    def test_initial_len_is_0(self):
        self.assertEqual(0, len(self.uut))

    def test_insertion_increses_size_to_1(self):
        self.uut.insert(self.mock_hashes_to(), 42)

    def test_collisions_are_handled(self):
        first = self.mock_hashes_to(1)
        second = self.mock_hashes_to(1)
        self.uut.insert(first, "spam")
        self.uut.insert(second, "eggs")
        self.assertEqual("spam", self.uut.get(first))
        self.assertEqual("eggs", self.uut.get(second))

    def test_inserting_items_with_a_higher_value_works(self):
        item = self.mock_hashes_to(99)
        self.uut.insert(item, 42)

        self.assertEqual(42, self.uut.get(item))

    def test_when_at_doubling_size_then_the_capacity_doubles(self):
        for i in xrange(11):
            self.uut.insert(i, "_")

        self.assertEqual(16, self.uut.capacity())

        self.uut.insert(12, "_")

        self.assertEqual(32, self.uut.capacity())
        self.assertEqual(12, len(self.uut))

    def test_len_is_0_after_delete_of_empty(self):
        self.uut.delete("foo")
        self.assertEqual(0, len(self.uut))

    def test_len_is_0_after_delete_of_only_item(self):
        self.uut.insert("foo", "_")
        self.uut.delete("foo")
        self.assertEqual(0, len(self.uut))

    def test_len_is_0_after_delete_of_only_item_twice(self):
        self.uut.insert("foo", "_")
        self.uut.delete("foo")
        self.uut.delete("foo")
        self.assertEqual(0, len(self.uut))
Ejemplo n.º 6
0
class TestHashMapMethods(unittest.TestCase):
    def setUp(self):
        self.hash = HashMap()
        self.hash["first"] = 1
        self.hash["second"] = 2
        self.hash["third"] = 3

    def test_get_gets_by_key(self):
        self.assertEqual(self.hash["first"], 1)
        self.assertEqual(self.hash["second"], 2)
        self.assertEqual(self.hash["third"], 3)

    def test_get_returns_none_for_absent_keys(self):
        self.assertIsNone(self.hash["fourth"])

    def test_set_sets_key_value_pair(self):
        self.hash["fourth"] = 4
        self.assertIsNone(self.hash[4])
        self.assertEqual(self.hash["fourth"], 4)

    def test_set_overwrites_value(self):
        self.hash["one"] = 1
        self.hash["one"] = "one"
        self.assertEqual(self.hash["one"], "one")

    def test_set_works_with_various_data_types(self):
        self.hash["fourth"] = 4
        self.hash[5] = 5
        self.assertEqual(self.hash["fourth"], 4)
        self.assertEqual(self.hash[5], 5)

    def test_include(self):
        self.assertTrue(self.hash.include("first"))
        self.assertFalse(self.hash.include("fourth"))

    def test_delete(self):
        self.assertEqual(self.hash["first"], 1)
        self.hash.delete("first")
        self.assertIsNone(self.hash["first"])

    def test_count_keeps_count_with_insertions(self):
        self.assertEqual(self.hash.count, 3)
        self.hash["fifth"] = 5
        self.assertEqual(self.hash.count, 4)

    def test_count_does_not_change_with_update(self):
        self.hash["first"] = 2
        self.assertEqual(self.hash.count, 3)

    def test_count_keeps_count_with_deletions(self):
        self.hash.delete("first")
        self.assertEqual(self.hash.count, 2)

    def test_resize_increases_length_of_store(self):
        i = 10
        while i < 17:
            self.hash[i] = i + 1
            i += 1

        self.assertEqual(len(self.hash.store), 16)

    def test_resize_rehashes_values(self):
        contents = []
        keys = ["first", "second", "third"]
        for key in keys:
            contents.append([key, self.hash[key]])
        self.hash.resize()

        for pair in contents:
            key, val = pair
            self.assertEqual(val, self.hash[key])

    def test___str__(self):
        expected_pairs = ["'first': 1", "'second': 2", "'third': 3"]
        actual_pairs = str(self.hash).split(", ")
        self.assertEqual(actual_pairs.sort(), expected_pairs.sort())
Ejemplo n.º 7
0
from hash_map import HashMap

# A basic demo of the methods in our hashmap class
hash_map = HashMap()
print "Welcome to a brief tutorial of our hashmap!\n"
print "At the beginning the hashmap is: " + str(hash_map)

hash_map["AAPL"] = 100
hash_map["GOOG"] = 200
hash_map["SP500"] = 175.75
print "After inserting our positions: " + str(hash_map)

hash_map["GOOG"] = 400
print "After doubling our number of shares in Google: " + str(hash_map)

hash_map.delete("AAPL")
print "After selling all of our shares in Apple: " + str(hash_map)

other_hash_map = HashMap()
other_hash_map["GOOG"] = 100
other_hash_map["DIS"] = 500
print "My friend recommends a different set of positions: " + str(
    other_hash_map)

hash_map.update(other_hash_map)
print "Our positions after updating with friend's recommendations: " + str(
    hash_map)

print "A list of tickers of our positions: " + str(hash_map.keys())
print "A list of the number of shares for each position: " + str(
    hash_map.values())
Ejemplo n.º 8
0
class HashMapTests(unittest.TestCase):
    def setUp(self):
        self.hash_map = HashMap()

    def tearDown(self):
        self.hash_map = None

    # test creation of empty hashmap
    def test_create_hash_map(self):
        self.assertTrue(self.hash_map.is_empty())
        self.assertEqual(len(self.hash_map), 0)

    # test insertion of key into hashmap and getter method
    def test_can_insert_into_hash_map(self):
        self.assertFalse(self.hash_map.has_key("test"))
        self.hash_map["test"] = "testing"
        self.assertTrue(self.hash_map.has_key("test"))
        self.assertEqual(len(self.hash_map), 1)
        self.assertEqual("testing", self.hash_map["test"])

    # test updating of key that already exists in hashmap
    def test_can_update_key_in_hash_map(self):
        self.hash_map["test"] = "testing"
        self.hash_map["test"] = "testing123"
        self.assertEqual("testing123", self.hash_map["test"])

    # test deleting of key in hashmap
    def test_can_delete_key_in_hash_map(self):
        self.hash_map["test"] = "testing"
        self.hash_map.delete("test")
        self.assertFalse(self.hash_map.has_key("test"))
        self.assertIsNone(self.hash_map.get("test"))

    # test that number of buckets grows after number of key/value pairs
    # becomes greater than number of buckets
    def test_hash_map_resize_after_insert(self):
        self.assertEqual(8, self.hash_map.num_buckets())

        i = 1
        while i <= 9:
            self.hash_map[i] = i
            i += 1

        self.assertEqual(16, self.hash_map.num_buckets())

    # test that number of buckets shrinks after number of key/value pairs
    # becomes less than one quarter of the number of buckets
    def test_hash_map_shrink_after_delete(self):
        i = 1
        while i <= 9:
            self.hash_map[i] = i
            i += 1

        while i > 0:
            self.hash_map.delete(i)
            i -= 1

        self.assertEqual(8, self.hash_map.num_buckets())

    # test that update method incorporates key/value pairs of another hashmap
    def test_hash_map_updates_with_other_hash_map(self):
        self.hash_map["test"] = "testing"
        other_hash_map = HashMap()
        other_hash_map["test"] = "testing123"
        other_hash_map["another test"] = "another testing123"
        self.hash_map.update(other_hash_map)
        self.assertEqual("testing123", self.hash_map["test"])
        self.assertEqual(["testing123", "another testing123"],
                         self.hash_map.values())