Coding

Could you demonstrate how to code a hash table in Python?

Machine Learning Engineer

Google

Twilio

FactSet

Illumina

Glovo

Zoom

Did you come across this question in an interview?

Answers

Expert Answer

Anonymous

5Exceptional
class HashTable:
    def __init__(self, size=10):
        """Initialize the hash table with a specified size."""
        self.size = size
        self.table = [[] for _ in range(self.size)]  # Create a list of empty buckets

    def _hash(self, key):
        """Hash the key to obtain an index."""
        return hash(key) % self.size

    def insert(self, key, value):
        """Insert a key-value pair into the hash table."""
        index = self._hash(key)
        for i, (k, v) in enumerate(self.table[index]):
            if k == key:  # Update the value if the key already exists
                self.table[index][i] = (key, value)
                return
        self.table[index].append((key, value))  # Add a new key-value pair

    def get(self, key):
        """Retrieve the value associated with a given key."""
        index = self._hash(key)
        for k, v in self.table[index]:
            if k == key:
                return v  # Return the value if the key is found
        return None  # Return None if the key is not found

    def remove(self, key):
        """Remove a key-value pair from the hash table."""
        index = self._hash(key)
        for i, (k, v) in enumerate(self.table[index]):
            if k == key:
                del self.table[index][i]  # Remove the key-value pair
                return True  # Indicate successful removal
        return False  # Indicate that the key was not found

    def __repr__(self):
        """String representation of the hash table."""
        return "{ " + ", ".join(f"{k}: {v}" for bucket in self.table for k, v in bucket) + " }"

# Example usage
hash_table = HashTable()
hash_table.insert("name", "Alice")
hash_table.insert("age", 30)
hash_table.insert("city", "New York")

print(hash_table)  # Output: { name: Alice, age: 30, city: New York }
print(hash_table.get("name"))  # Output: Alice
print(hash_table.get("age"))  # Output: 30

hash_table.remove("city")
print(hash_table)  # Output: { name: Alice, age: 30 }

  • Could you demonstrate how to code a hash table in Python?
  • What would be your approach to writing a Python script that implements a hash table?
  • Can you show the syntax for creating a hash table in Python?
  • Please provide a Python snippet that results in a functioning hash table.
  • How would you go about coding a functional hash table in Python?
  • In Python, how do you script out the implementation of a hash table?
  • What's the process for writing Python code that constructs a hash table?
  • Can you construct a hash table using Python code?
  • How do you write a Python program to establish a hash table?
  • Could you draft a Python code that sets up a hash table?
  • Write a code to implement a hash table in Python
Try Our AI Interviewer

Prepare for success with realistic, role-specific interview simulations.

Try AI Interview Now

Interview question asked to Machine Learning Engineers interviewing at Splunk, Illumina, Zillow and others: Could you demonstrate how to code a hash table in Python?.