python脚本"导入hashmap"打印' 0& - 39' s

时间:2014-11-23 11:53:23

标签: python

运行只有一行代码的python脚本时

import hashmap

,它打印出来就像这样

0
-1
0
-1

以及更多0-1 s

有线,我无法弄清楚原因。这是hashmap.py文件:

def new(num_buckets=256):
    """Initializes a Map with 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) % -2# len(aMap) # WHAT'S THIS?!!!

aMap = new()
for i in range(0, 300):
    print hash_key(aMap, "abc%r" % i)

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 the 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)    # what if just "default"??????
    return v 

def set(aMap, key, value):
    """set 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

2 个答案:

答案 0 :(得分:0)

原因如下:

aMap = new()
for i in range(0, 300):
    print hash_key(aMap, "abc%r" % i)

导入模块时,将执行所有顶级代码。特别是,您的hash_key函数会返回x % -2(其中x是一些数字量)。因此,上面的代码段会打印0-1 300次。

即使这是期望的行为,您的哈希函数仍然是错误的。看看这一行:

hash(key) % -2# len(aMap) # WHAT'S THIS?!!!

以下是"这是什么的答案?" x % len(aMap)部分用于约束[0; len(aMap))中的值} range,以便可以用它来选择合适的存储桶。通过使用-2,您将在hashmap中仅选择两个存储桶,第一个和最后一个。这将在闭合和开放寻址中增加冲突解决的重大开销。

答案 1 :(得分:0)

您需要删除脚本的这一部分或将其添加到if __name__ == '__main__':块:

aMap = new()
for i in range(0, 300):
    print hash_key(aMap, "abc%r" % i)

导入脚本(模块)时,会执行其代码。因此,您看到的数字是上述代码的输出。