class intDict(object):
"""A dictionary with integer keys."""
def __init__(self, numBuckets):
"""Creates empty dictionary."""
self.buckets = []
self.numBuckets = numBuckets
for i in range(numBuckets):
self.buckets.append([])
def addEntry(self, dictKey, dictVal):
"""Assumes dictKey an int. Adds an entry."""
hashBucket = self.buckets[dictKey%self.numBuckets]
for i in range(len(hashBucket)):
if hashBucket[i][0] == dictKey:
hashBucket[i] = (dictKey, dictVal)
return
hashBucket.append((dictKey, dictVal))
def getValue(self, dictKey):
"""Assumes dictKey an int. Returns entry associated with
the key dictKey."""
hashBucket = self.buckets[dictKey%self.numBuckets]
for e in hashBucket:
if e[0] == dictKey:
return e[1]
return None
def __str__(self):
result = '{'
for b in self.buckets:
for e in b:
result = result + str(e[0]) + ':' + str(e[1]) + ','
return result[:1] + '}'
import random
D = intDict(29)
for i in range(20):
key = random.randint(0, 10**5)
D.addEntry(key, i)
print "The value of the intDict is: "
print D
print '\n', "The buckets are: "
for hashBucket in D.buckets:
print ' ', hashBucket
有人可以向我解释一下addEntry(self, dictKey, dictVal)
的作用是什么吗?如何。
我是一般编程的新手,遵循John Guttags使用Python进行计算和编程的介绍,目前仍然坚持这一点。
顺便说一句,print "The value of intDict is: "
,运行时,只打印29个空列表。那是为什么?