Решение на BiDict от Петко Пъдевски

Обратно към всички решения

Към профила на Петко Пъдевски

Резултати

  • 6 точки от тестове
  • 0 бонус точки
  • 6 точки общо
  • 15 успешни тест(а)
  • 1 неуспешни тест(а)

Код

'''
Created on Apr 17, 2012
@author: ppadevski
'''
#!/usr/bin/env python3
class BiDict(object):
'''
Bidirectional mapping dictionary.
'''
def __init__(self, *args, **kwargs):
self._primary = {}
self._secondary = {}
dictionary = dict(*args, **kwargs)
for k, v in dictionary.items():
self[k] = v
def __len__(self):
'''
Return the number of items in the dictionary.
'''
return len(self._primary)
def __getitem__(self, key):
'''
Return the item of the dictionary with key key.
Raises a KeyError if key is not in the map.
'''
return self._primary[key]
def __setitem__(self, key, value):
'''
Set dictinary[key] to value.
'''
# If there already is such a key/value pair, remove it
try:
old_value = self._primary[key]
except KeyError:
pass
else:
del self._secondary[old_value]
# If there already is such a key/value pair, remove it
try:
old_key = self._secondary[value]
except KeyError:
pass
else:
del self._primary[old_key]
self._primary[key] = value
self._secondary[value] = key
def __contains__(self, key):
'''
Return True if dictinary has a key key, else False.
'''
return key in self._primary
def __delitem__(self, key):
'''
Remove dictionary[key] from the dictionary.
Raises a KeyError if key is not in the map.
'''
value = self._primary[key]
del self._primary[key]
del self._secondary[value]
def __iter__(self):
'''
Return an iterator over the keys of the dictionary.
'''
return iter(self._primary)
def clear(self):
'''
Remove all items from the dictionary.
'''
self._primary.clear()
self._secondary.clear()
def copy(self):
'''
Return a shallow copy of the dictionary.
'''
return BiDict(self._primary)
def get(self, key, default=None):
'''
Return the value for key if key is in the dictionary, else default.
If default is not given, it defaults to None,
so that this method never raises a KeyError.
'''
return self._primary.get(key, default)
def items(self):
'''
Return a new view of the dictionary’s items ((key, value) pairs).
'''
return self._primary.items()
def keys(self):
'''
Return a new view of the dictionary’s keys.
'''
return self._primary.keys()
def pop(self, key, default=None):
'''
If key is in the dictionary, remove it and return its value,
else return default.
If default is not given and key is not in the dictionary,
a KeyError is raised.
'''
# If this raises KeyError, we're ok.
# If it doesn't, value is not found and default is given, secondary
# may not contain it as a key
value = self._primary.pop(key, default)
try:
del self._secondary[value]
except KeyError:
pass
return value
def popitem(self):
'''
Remove and return an arbitrary (key, value) pair from the dictionary.
'''
key, value = self._primary.popitem()
# This must always be present
del self._secondary[value]
return key, value
def setdefault(self, key, default=None):
'''
If key is in the dictionary, return its value.
If not, insert key with a value of default and return default.
default defaults to None.
'''
# We expect that if default is not given and key is not in the
# dictionary, that this would raise KeyError
value = self._primary.setdefault(key, default)
self._secondary[value] = key
return value
def update(self, other=None):
'''
Update the dictionary with the key/value pairs from other,
overwriting existing keys. Returns None.
'''
self._primary.update(other)
another_bidict = BiDict(self._primary)
self._primary = another_bidict._primary
self._secondary = another_bidict._secondary
def values(self):
'''
Returns a new view of the dictionary’s values.
'''
return self._primary.values()
def inverse(self):
'''
Inverts the BiDict
'''
self._primary, self._secondary = self._secondary, self._primary
def __str__(self):
return '{0}({1})'.format(self.__class__.__name__, self._primary)
__repr__ = __str__
def __eq__(self, other):
return self._primary == other._primary
def __neq__(self, other):
return self._primary != other._primary

Лог от изпълнението

..E.............
======================================================================
ERROR: test_circular_values (__main__.BiDictTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/tmp/test20120627-22085-vb12fe", line 49, in test_circular_values
    circular = self.solutions.BiDict({1: 2, 2: 3, 3: 1})
AttributeError: 'BiDictTestCase' object has no attribute 'solutions'

----------------------------------------------------------------------
Ran 16 tests in 0.002s

FAILED (errors=1)

История (1 версия и 0 коментара)

Петко обнови решението на 18.04.2012 21:24 (преди над 12 години)

+'''
+Created on Apr 17, 2012
+
+@author: ppadevski
+'''
+#!/usr/bin/env python3
+
+
+class BiDict(object):
+ '''
+ Bidirectional mapping dictionary.
+ '''
+
+ def __init__(self, *args, **kwargs):
+ self._primary = {}
+ self._secondary = {}
+
+ dictionary = dict(*args, **kwargs)
+ for k, v in dictionary.items():
+ self[k] = v
+
+ def __len__(self):
+ '''
+ Return the number of items in the dictionary.
+ '''
+ return len(self._primary)
+
+ def __getitem__(self, key):
+ '''
+ Return the item of the dictionary with key key.
+ Raises a KeyError if key is not in the map.
+ '''
+ return self._primary[key]
+
+ def __setitem__(self, key, value):
+ '''
+ Set dictinary[key] to value.
+ '''
+ # If there already is such a key/value pair, remove it
+ try:
+ old_value = self._primary[key]
+ except KeyError:
+ pass
+ else:
+ del self._secondary[old_value]
+
+ # If there already is such a key/value pair, remove it
+ try:
+ old_key = self._secondary[value]
+ except KeyError:
+ pass
+ else:
+ del self._primary[old_key]
+
+ self._primary[key] = value
+ self._secondary[value] = key
+
+ def __contains__(self, key):
+ '''
+ Return True if dictinary has a key key, else False.
+ '''
+ return key in self._primary
+
+ def __delitem__(self, key):
+ '''
+ Remove dictionary[key] from the dictionary.
+ Raises a KeyError if key is not in the map.
+ '''
+ value = self._primary[key]
+ del self._primary[key]
+ del self._secondary[value]
+
+ def __iter__(self):
+ '''
+ Return an iterator over the keys of the dictionary.
+ '''
+ return iter(self._primary)
+
+ def clear(self):
+ '''
+ Remove all items from the dictionary.
+ '''
+ self._primary.clear()
+ self._secondary.clear()
+
+ def copy(self):
+ '''
+ Return a shallow copy of the dictionary.
+ '''
+ return BiDict(self._primary)
+
+ def get(self, key, default=None):
+ '''
+ Return the value for key if key is in the dictionary, else default.
+ If default is not given, it defaults to None,
+ so that this method never raises a KeyError.
+ '''
+ return self._primary.get(key, default)
+
+ def items(self):
+ '''
+ Return a new view of the dictionary’s items ((key, value) pairs).
+ '''
+ return self._primary.items()
+
+ def keys(self):
+ '''
+ Return a new view of the dictionary’s keys.
+ '''
+ return self._primary.keys()
+
+ def pop(self, key, default=None):
+ '''
+ If key is in the dictionary, remove it and return its value,
+ else return default.
+ If default is not given and key is not in the dictionary,
+ a KeyError is raised.
+ '''
+ # If this raises KeyError, we're ok.
+ # If it doesn't, value is not found and default is given, secondary
+ # may not contain it as a key
+ value = self._primary.pop(key, default)
+ try:
+ del self._secondary[value]
+ except KeyError:
+ pass
+ return value
+
+ def popitem(self):
+ '''
+ Remove and return an arbitrary (key, value) pair from the dictionary.
+ '''
+ key, value = self._primary.popitem()
+ # This must always be present
+ del self._secondary[value]
+ return key, value
+
+ def setdefault(self, key, default=None):
+ '''
+ If key is in the dictionary, return its value.
+ If not, insert key with a value of default and return default.
+ default defaults to None.
+ '''
+ # We expect that if default is not given and key is not in the
+ # dictionary, that this would raise KeyError
+ value = self._primary.setdefault(key, default)
+ self._secondary[value] = key
+ return value
+
+ def update(self, other=None):
+ '''
+ Update the dictionary with the key/value pairs from other,
+ overwriting existing keys. Returns None.
+ '''
+ self._primary.update(other)
+ another_bidict = BiDict(self._primary)
+ self._primary = another_bidict._primary
+ self._secondary = another_bidict._secondary
+
+ def values(self):
+ '''
+ Returns a new view of the dictionary’s values.
+ '''
+ return self._primary.values()
+
+ def inverse(self):
+ '''
+ Inverts the BiDict
+ '''
+ self._primary, self._secondary = self._secondary, self._primary
+
+ def __str__(self):
+ return '{0}({1})'.format(self.__class__.__name__, self._primary)
+
+ __repr__ = __str__
+
+ def __eq__(self, other):
+ return self._primary == other._primary
+
+ def __neq__(self, other):
+ return self._primary != other._primary