如何解决hashmap模块中的一些问题?

2024-06-17 12:35:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我在做编程书上的练习。 我写了一个代码,但有些步骤我不明白。在

我创建的这段代码是一个名为hashmap的模块:

def new(num_buckets=256):
    """Initializes a Map with the given number of buckets."""
    aMap = []
    for i in range(0, num_buckets):
        aMap.append([])
    return aMap

def hash_key(aMap, key):
    """Given a key this will create a number and then convert it to
    an index for the aMap's buckets."""
    return hash(key) % len(aMap)

def get_bucket(aMap, key):
    """Given a key, find the bucket where it would go."""
    bucket_id = hash_key(aMap, key)
    return aMap[bucket_id]

def get_slot(aMap, key, default=None):
    """
    Returns the index, key, and value of a slot found in a bucket.
    Returns -1, key, and default (None if not set) when not found.
    """
    bucket = get_bucket(aMap, key)

    for i, kv in enumerate(bucket):
        k, v = kv
        if key == k:
            return i, k, v

    return -1, key, default

def get(aMap, key, default=None):
    """Gets the value in a bucket for the given key, or the default."""
    i, k, v = get_slot(aMap, key, default=default)
    return v

def set(aMap, key, value):
    """Sets the key to the value, replacing any existing value."""
    bucket = get_bucket(aMap, key)
    i, k, v = get_slot(aMap, key)

    if i >= 0:
        # the key exists, replace it
        bucket[i] = (key, value)
    else:
        # the key does not, append to create it
        bucket.append((key, value))

def delete(aMap, key):
    """Deletes the given key from the Map."""
    bucket = get_bucket(aMap, key)

    for i in xrange(len(bucket)):
        k, v = bucket[i]
        if key == k:
            del bucket[i]
            break

def list(aMap):
    """Prints out what's in the Map."""
    for bucket in aMap:
        if bucket:
            for k, v in bucket:
                print k, v

1)为什么函数new(num_buckets=256)中有关键字作为参数? 如果我在函数的中间设置num_buckets作为变量,256作为一个值呢?放在哪里重要吗?在

^{pr2}$

2)为什么aMap的大小是256?是故意的还是偶然的?在

3)函数的意义是什么? 这种方式不能保证密钥将在带有“余数索引”的bucket中。在

For example.

^{3}$

运行函数hash_key后,“余数索引”将是1。但是键10不在第一个bucket中。在

我是Python新手。我希望你的帮助。


Tags: thekeyindefaultforgetreturnif
2条回答
  1. 这只是一个默认参数。它在代码执行时绑定一次,并允许函数的用户不显式地设置它。如果在代码中设置了它,则用户必须在调用函数时进行设置。

  2. 256只是个数字。它可能很适合记忆,所以它被选中了。我记得Java也为HashMap的后备桶使用了2^n个大小,但我不信。

  3. 我不太明白你的例子。在插入和从映射中检索时使用哈希键-只是为了得到正确的bucket。然后像与列表一样进行比较(因为bucket实际上是列表)。

(1)和;(2) 这是一个可选的输入参数,是对一般用途的适当桶数的猜测。如果不带参数调用“new”,则num_bucket将为256个。如果提供了参数,则num_bucket将采用该值。在

(3)我想你可能对散列有点困惑。散列函数的作用是提供一个对密钥进行编码的整数。散列值应该在整个给定的整数范围内扩展密钥集。例如,“9”可能映射到12;“10”可能映射到301。后者将转换为45(301%256)。在

根据您提供的数据,“10”将映射到键10,而不是1。你能解释一下余数指数是怎么得到1的吗?在

相关问题 更多 >