如何在手动实现的散列 table 中找到最大值?

How to find the max value in a hash table that is manually implemented?

大家好,我是 Python 的新手,我实现了一个哈希 table 来计算单词中字母出现的次数。

例如散列 table 当前存储此:

{l:1, r:1, t:1, u:1, a:1, c:1, d:2, e:1, }

我想在散列 table 中找到最大值,即 2。我实现了一个迭代器,因此我可以遍历散列 table。我设法找到了这样的最大值:

编辑:我用设置项实现了哈希table class,获取项功能。

class HashTableQuadratic:

def __init__(self, size=10):
    self.count = 0
    self.table_size = size
    self.array = build_array(self.table_size)
    self.collision=0
    self.totalProbeLength=0

 //some code here


tempList=[]
for item in hashTable:
if item!=None:
    tempList.append(item[1])
maxNum=max(tempList)
print(maxNum)

但是有没有更好的方法来做到这一点而不使用 tempList 和 max 内置函数?

假设您的 class 与 collections.Counter 相同,您可以这样简单地使用 max

max(hashTable.items(), key=lambda item: item[1])

这将 return ('d', 2) 以您的示例为例。如果您不想知道哪个键具有最大值,您可以简化它。

我们将所有项目作为 (key, value) 对传递,并使用 maxkey 参数告诉它按值比较项目。

您的 hashTable 对象似乎是可迭代的键值对。

首先,不是你的四行代码:

tempList=[]
for item in hashTable:
if item!=None:
    tempList.append(item[1])

…相当于一行理解:

tempList = [item[1] for item in hashTable if item is not None]

将它变成惰性迭代器而不是在内存中构建列表是微不足道的:

it = (item[1] for item in hashTable if item is not None)

您可以直接在 max 调用中内联:

maxNum = max(item[1] for item in hashTable if item is not None)

作为旁注,请注意我使用 item is not None 而不是 item != None。您几乎从不 想要将None==!= 进行比较。经验法则是:

  • 如果您想要任何真值,请使用 if item
  • 如果您想要任何非 None 值,请使用 if item is not None
  • 如果您想要任何非 None 值,同时明确允许其他 类 覆盖 __eq__ 并与 None 进行比较,请使用 if item != None.

但是,值得注意的是,如果您想要构建自定义哈希 table,您可能希望它表现得像一个字典——或者至少像一个 Mapping。实现 Mapping 接口非常简单,这意味着您的对象可以像字典一样鸭式输入。

而且,如果这样做,您可以使用与 dict 相同的代码:

maxNum = max(hashTable.values())