Skip to content

Instantly share code, notes, and snippets.

@campbellmarianna
Created May 20, 2019 02:31
Show Gist options
  • Save campbellmarianna/36cbc13b041a4683388524b4a48a3e3c to your computer and use it in GitHub Desktop.
Save campbellmarianna/36cbc13b041a4683388524b4a48a3e3c to your computer and use it in GitHub Desktop.
get a value from a hash table
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