Skip to content

Instantly share code, notes, and snippets.

@yoavram
Created November 27, 2011 15:22
Show Gist options
  • Save yoavram/1397685 to your computer and use it in GitHub Desktop.
Save yoavram/1397685 to your computer and use it in GitHub Desktop.
A simple implementation of Multimap in Pyhthon, used as an example for OOP
class Multimap:
def __init__(self):
'''Create an empty Multimap'''
self.inner = inner
def get(self, key):
'''Return list of values associated with key'''
return self.inner.get(key, [])
def count(self, key):
'''Returns the number of values associated with key'''
return len(self.get(key))
def put(self, key, value):
'''Adds value to the list of values associated with key'''
value_list = self.get(key)
if value not in value_list:
value_list.append(value)
self.inner[key] = value_list
def put_all(self, key, values):
'''Adds all values to the list of values associated with key'''
for v in values:
self.put(key, v)
def remove(self, key, value):
'''Remove value from the list of values associated with key.
Returns True is the Multimap changed, False otherwise'''
value_list = self.get(key)
if value in value_list:
value_list.remove(value)
self.inner[key] = value_list
return True
return False
def has_key(self, key):
'''Returns True if key exists in the map'''
return self.inner.has_key(key)
def __len__(self):
'''Returns the number of keys in the map'''
return len(self.inner)
def __str__(self):
'''Converts the map to a string'''
return str(self.inner)
def __cmp__(self, other):
'''Compares the map with another map'''
return self.inner.cmp(other)
def __contains__(self, key):
'''Returns True if key exists in the map'''
return self.has_key(k)
def clear(self):
'''Clears the map'''
self.inner.clear()
if __name__=='__main__':
m = Multimap()
m.put('Israel', 'Tel-Aviv')
m.put('Israel', 'Jerusalem')
m.put('France', 'Paris')
m.put_all('England',('London', 'Manchester', 'Moscow'))
m.remove('England', 'Moscow')
print m
print m.get('Israel')
print 'Cities of England:', m['England']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment