Решение на BiDict от Николай Колев

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

Към профила на Николай Колев

Резултати

  • 3 точки от тестове
  • 0 бонус точки
  • 3 точки общо
  • 7 успешни тест(а)
  • 9 неуспешни тест(а)

Код

import collections
def _is_hashable(obj):
return isinstance(obj, collections.Hashable)
class BiDict:
"""
Dictionary collection which allows to invert the key-value pairs
"""
def __init__(self, dictionary = dict()):
dict_values = dictionary.values()
if len(dict_values) > len(set(dict_values)):
raise ValueError('The dictionary values must be unique')
if not all(_is_hashable(x) for x in dict_values):
raise TypeError('Unhashable type into the dictionary values')
self.dictionary = dict(dictionary)
def __contains__(self, element):
return element in self.dictionary
def __getitem__(self, key):
return self.dictionary[key]
def __setitem__(self, key, value):
if value in self.dictionary.values():
raise ValueError('The dictionary values must be unique')
if not _is_hashable(value):
raise TypeError('Unhashable type into the dictionary values')
self.dictionary[key] = value
def __delitem__(self, key):
del self.dictionary[key]
def __eq__(self, other):
return self.dictionary == other
def __iter__(self):
return iter(dict(self.dictionary))
def __len__(self):
return len(self.dictionary)
def __str__(self):
return str(self.dictionary)
def pop(self, key):
return self.dictionary.pop(key)
def clear(self):
self.dictionary.clear()
def items(self):
return self.dictionary.items()
def keys(self):
return self.dictionary.keys()
def values(self):
return self.dictionary.values()
def inverse(self):
"""
Invert the key-value pairs of the dictionary collection
"""
self.dictionary = {self.dictionary[k] :k for k in self.dictionary}

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

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

======================================================================
ERROR: test_copied_circular_values (__main__.BiDictTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/tmp/test20120627-22085-9bzlmv", line 56, in test_copied_circular_values
    inversed_circular = circular.copy()
AttributeError: 'BiDict' object has no attribute 'copy'

======================================================================
ERROR: test_hashing_self (__main__.BiDictTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/tmp/test20120627-22085-9bzlmv", line 65, in test_hashing_self
    self.assertRaises(TypeError, self.person.update, {'clone': self.person})
AttributeError: 'BiDict' object has no attribute 'update'

======================================================================
ERROR: test_insert_existing_key_with_existing_value (__main__.BiDictTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/tmp/test20120627-22085-9bzlmv", line 74, in test_insert_existing_key_with_existing_value
    new_person = self.person.copy()
AttributeError: 'BiDict' object has no attribute 'copy'

======================================================================
ERROR: test_insert_existing_key_with_none_existing_value (__main__.BiDictTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/tmp/test20120627-22085-9bzlmv", line 81, in test_insert_existing_key_with_none_existing_value
    new_person = self.person.copy()
AttributeError: 'BiDict' object has no attribute 'copy'

======================================================================
ERROR: test_insert_none_existing_key_with_existing_value (__main__.BiDictTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/tmp/test20120627-22085-9bzlmv", line 88, in test_insert_none_existing_key_with_existing_value
    new_person = self.person.copy()
AttributeError: 'BiDict' object has no attribute 'copy'

======================================================================
ERROR: test_insert_none_existing_key_with_none_existing_value (__main__.BiDictTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/tmp/test20120627-22085-9bzlmv", line 95, in test_insert_none_existing_key_with_none_existing_value
    new_person = self.person.copy()
AttributeError: 'BiDict' object has no attribute 'copy'

======================================================================
ERROR: test_invalid_value (__main__.BiDictTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/tmp/test20120627-22085-9bzlmv", line 62, in test_invalid_value
    self.assertRaises(TypeError, self.person.update, {'sports': ['boxing',]})
AttributeError: 'BiDict' object has no attribute 'update'

======================================================================
FAIL: test_has_dict_attrs (__main__.BiDictTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/tmp/test20120627-22085-9bzlmv", line 70, in test_has_dict_attrs
    self.assertIn('copy', dir(self.person))
AssertionError: 'copy' not found in ['__class__', '__contains__', '__delattr__', '__delitem__', '__dict__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'clear', 'dictionary', 'inverse', 'items', 'keys', 'pop', 'values']

----------------------------------------------------------------------
Ran 16 tests in 0.003s

FAILED (failures=1, errors=8)

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

Николай обнови решението на 10.04.2012 22:00 (преди над 8 години)

+import collections
+
+def _is_hashable(obj):
+ return isinstance(obj, collections.Hashable)
+
+class BiDict:
+ """
+ Dictionary collection which allows to invert the key-value pairs
+ """
+ def __init__(self, dictionary = dict()):
+ dict_values = dictionary.values()
+ if len(dict_values) > len(set(dict_values)):
+ raise ValueError('The dictionary values must be unique')
+ if not all(_is_hashable(x) for x in dict_values):
+ raise TypeError('Unhashable type into the dictionary values')
+ self.dictionary = dict(dictionary)
+
+ def __contains__(self, element):
+ return element in self.dictionary
+
+ def __getitem__(self, key):
+ return self.dictionary[key]
+
+ def __setitem__(self, key, value):
+ if value in self.dictionary.values():
+ raise ValueError('The dictionary values must be unique')
+ if not _is_hashable(value):
+ raise TypeError('Unhashable type into the dictionary values')
+ self.dictionary[key] = value
+
+ def __delitem__(self, key):
+ del self.dictionary[key]
+
+ def __eq__(self, other):
+ return self.dictionary == other
+
+ def __iter__(self):
+ return iter(dict(self.dictionary))
+
+ def __len__(self):
+ return len(self.dictionary)
+
+ def __str__(self):
+ return str(self.dictionary)
+
+ def pop(self, key):
+ return self.dictionary.pop(key)
+
+ def clear(self):
+ self.dictionary.clear()
+
+ def items(self):
+ return self.dictionary.items()
+
+ def keys(self):
+ return self.dictionary.keys()
+
+ def values(self):
+ return self.dictionary.values()
+
+ def inverse(self):
+ """
+ Invert the key-value pairs of the dictionary collection
+ """
+ self.dictionary = {self.dictionary[k] :k for k in self.dictionary}