【问题标题】:Understanding Hash Tables with python as a reference以python为参考了解哈希表
【发布时间】:2017-10-05 05:21:29
【问题描述】:

我正在通过data structures 进行在线讲座,我想确认我对hash table 的理解。

我知道hash table 将使用hashing 函数将所有可能的键域缩减为一组m,并使用chaining 解析collisions

我似乎无法想象其中的m 部分。假设我在python 中创建了一个空的dict()python 是否创建了一个包含一些预定义数量的空槽的表?

【问题讨论】:

标签: python algorithm hash hashtable hash-collision


【解决方案1】:

概述

可以在 2017 Pycon 演讲Modern Python Dictionaries A confluence of a dozen great ideas 中找到有关如何实现 Python 字典的概述。

如何可视化减少

我了解哈希表将使用哈希函数将所有可能键的域减少到集合 m 并使用链接来解决冲突。 ...我似乎无法想象其中的 m 部分。

最简单的可视化是使用m == 2,以便散列将键分为两组:

>>> from pprint import pprint
>>> def hash(n):
        'Hash a number into evens or odds'
        return n % 2

>>> table = [[], []]
>>> for x in [10, 15, 12, 41, 80, 13, 40, 9]:
        table[hash(x)].append(x)

>>> pprint(table, width=25)
[[10, 12, 80, 40],
 [15, 41, 13, 9]]

在上面的例子中,八个键都被分为两组(偶数和赔率)。

该示例也适用于较大的 m 值,例如 m == 7:

>>> table = [[], [], [], [], [], [], []]
>>> for x in [10, 15, 12, 41, 80, 13, 40, 9]:
        table[x % 7].append(x)

>>> pprint(table, width=25)
[[],
 [15],
 [9],
 [10, 80],
 [],
 [12, 40],
 [41, 13]]

如你所见,上面的例子有两个空槽和有碰撞的槽。

空字典的表

假设我在 python 中创建了一个空的 dict()。 python 是否会创建一个包含一些预定义数量的空条目的表?

是的,Python 为一个空表创建了八个槽。在 Python 的源代码中,我们在cpython/Objects/dictobject.c 中看到了#define PyDict_MINSIZE 8

【讨论】:

    猜你喜欢
    • 2011-06-07
    • 2018-03-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-04
    • 1970-01-01
    • 2013-05-28
    • 1970-01-01
    • 2023-03-18
    相关资源
    最近更新 更多