Created
May 20, 2019 02:31
-
-
Save campbellmarianna/36cbc13b041a4683388524b4a48a3e3c to your computer and use it in GitHub Desktop.
get a value from a hash table
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def get(self, key): | |
"""Return the value associated with the given key, or raise KeyError. | |
Best case running time: O(1) if the key is found early in iterating through | |
the bucket | |
Worst case running time: O(n + i) for n nodes in the LinkedList because | |
we have to iterate over all n nodes, iterate over all the i items and check | |
to see whose data matches the given key""" | |
# Find the bucket the given key belongs in | |
index = self._bucket_index(key) | |
bucket = self.buckets[index] | |
# Find the entry with the given key in that bucket, if one exists | |
entry = bucket.find(lambda key_value: key_value[0] == key) | |
if entry is not None: # Found | |
# Return the given key's associated value | |
assert isinstance(entry, tuple) | |
assert len(entry) == 2 | |
return entry[1] | |
else: # Not found | |
raise KeyError('Key not found: {}'.format(key)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment