2014-11-23 6 views
0

, 그냥이파이썬 스크립트 "수입 해시 맵 '인쇄'는 0과 -1의

0 
-1 
0 
-1 
처럼 인쇄

이상 0s 및 -1s

이유는 알 수 없습니다. 여기

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 

답변

0

이유입니다 :

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

당신이 모듈을 가져

이 모든 최고 수준의 코드가 실행 여기에 hashmap.py 파일입니다. 특히 hash_key 함수는 x % -2을 반환합니다 (여기서 숫자는 x입니다). 따라서 위의 코드 조각은 0 또는 -1 중 300 번 인쇄됩니다.

원하는 동작이지만 해시 함수가 여전히 잘못되었습니다. 이 라인에 살펴 유무 : 여기

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

하면 에 대한 답은 "이게 뭐야?" : x % len(aMap) 부분은 [0; len(aMap)) 범위의 값을 제한하는 데 사용되므로 적절한 버킷을 선택하는 데 사용할 수 있습니다. -2을 사용하면 해시 맵에서 첫 번째와 마지막 두 개의 버킷 만 선택하게됩니다. 이로써 폐쇄 및 개방 주소 지정 모두에서 충돌 해결에 상당한 오버 헤드가 추가됩니다. 스크립트 (모듈)을 가져 오면

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

, 해당 코드가 실행됩니다

0

당신은 스크립트의이 부분을 제거하거나 if __name__ == '__main__': 블록에 추가해야합니다. 따라서 표시되는 숫자는 위 코드의 결과입니다.