将 is_empty 添加到哈希表

adding is_empty to hashtable

我正在尝试添加一个 is_empty(self) 方法。如果散列 table 没有将键映射到值,则 return 为真,否则为假。 这就是我目前所拥有的,我只是不确定如何使用 self 来处理 is_empty 函数。

class MyHashTable:

    def __init__(self, capacity): 
        self.capacity = capacity 
        self.slots = [None] * self.capacity

    def __str__(self): 
        return str(self.slots )

    def is_empty(self) 
        pass

由于self.slots是一个list,目标是测试所有元素都是None。我会建议:

def is_empty(self) 
   return self.slots.count(None) == len(self.slots)

请参阅 How to check if all items in the list are None? 了解我在那里和其他人的回答。

另一种方法可以使用名为 all() 的内置函数。您可以查看 reference 了解更多详情。

Return True if all elements of the iterable are true (or if the iterable is empty).

示例代码:

def is_empty(self) 
    return all(item is None for item in self.slots)