import random class intDict(object): """A dictionary with integer keys""" def __init__(self, numBuckts): """Create an empty dictionary""" self.buckets = [] self.numBuckets = numBuckts for i in range(numBuckts): 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): res = '' # Change 1 for b in self.buckets: for t in b: res = res + str(t[0]) + ':' + str(t[1]) + ',' return '{' + res[:-1] + '}' # Change 2 D = intDict(29) for i in range(20): #choose a random int in range(10**5) key = random.choice(range(10**5)) D.addEntry(key, i) print '\n', 'The buckets are:' for hashBucket in D.buckets: #violates abstraction barrier print ' ', hashBucket
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question