class Dictionary1: """ A dictionary represented with a Python list. Each list element is a tuple of two parts, the key and the value """ def __init__(self): #precondition(True) self.__listOfPairs = [] # "extending" constructor method: 'with' # d.withEntry(k, v) has all the key/value pairs of d, together with a new entry def withEntry(self, key, value): #precondition(True) result = Dictionary1() result.__listOfPairs = [ (key, value) ] + self.__listOfPairs return result # axioms: # Dictionary().lookup(x) === "No entry" # d.withEntry(k, v).lookup(x) === v, if k==x # or d.lookup(x), otherwise def lookup(self, key): #precondition(True) for pair in self.__listOfPairs: if pair[0] == key: return pair[1] return "No entry" # axioms: # d.put(k, v) --> new d is d.withEntry(k, v) def put(self, key, value): #precondition(True) self.__listOfPairs = [ (key, value) ] + self.__listOfPairs def __eq__(self,other): #precondition( isinstance(otherDictionary,Dictionary1) ) if len(self.rep) != len(other.rep): return False for x in self.rep, y in other.rep: if x != y or self.rep[x] != other.rep[y]: return False return True def __eq__(self,otherDictionary): precondition( isinstance(otherDictionary,Dictionary1) ) if len(self.rep) != len(otherDictionary.rep): return False for x in self.rep, y in otherDictionary.rep: if x != y or self.rep[x] != otherDictionary.rep[y]: return False return True
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