Решение на BiDict от Евгени Цаков

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

Към профила на Евгени Цаков

Резултати

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

Код

class BiDict(dict):
def __init__(self, *args):
dictionary = dict(*args)
for k, v in dictionary.items():
self[k] = v
def __setitem__(self, key, value):
if not value.__hash__:
raise TypeError("unhashable type: '{0}'".
format(type(value).__name__))
for k, v in self.items():
if v == value:
del self[k]
break
super(BiDict, self).__setitem__(key, value)
def __repr__(self):
return 'BiDict({0})'.format(super(BiDict, self).__repr__())
def update(self, E, **F):
if hasattr(E, 'keys'):
for k in E:
self[k] = E[k]
else:
for k, v in E:
self[k] = v
for k in F:
self[k] = F[k]
def copy(self):
return BiDict(super(BiDict, self).copy())
def setdefault(self, k, d=None):
if not d.__hash__:
raise TypeError("unhashable type: '{0}'".
format(type(d).__name__))
if k not in self:
self[k] = d
return d
def inverse(self):
old = self.copy()
self.clear()
for k, v in old.items():
super(BiDict, self).__setitem__(v, k)

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

..E.............
======================================================================
ERROR: test_circular_values (__main__.BiDictTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/tmp/test20120627-22085-c6x7vy", 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.003s

FAILED (errors=1)

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

Евгени обнови решението на 12.04.2012 11:47 (преди над 8 години)

+class BiDict(dict):
+ def __init__(self, *args):
+ dictionary = dict(*args)
+ for k, v in dictionary.items():
+ self[k] = v
+
+ def __setitem__(self, key, value):
+ if not value.__hash__:
+ raise TypeError("unhashable type: '{0}'".
+ format(type(value).__name__))
+
+ for k, v in self.items():
+ if v == value:
+ del self[k]
+ break
+
+ super(BiDict, self).__setitem__(key, value)
+
+ def __repr__(self):
+ return 'BiDict({0})'.format(super(BiDict, self).__repr__())
+
+ def update(self, E, **F):
+ if hasattr(E, 'keys'):
+ for k in E:
+ self[k] = E[k]
+ else:
+ for k, v in E:
+ self[k] = v
+
+ for k in F:
+ self[k] = F[k]
+
+ def copy(self):
+ return BiDict(super(BiDict, self).copy())
+
+ def setdefault(self, k, d=None):
+ if not d.__hash__:
+ raise TypeError("unhashable type: '{0}'".
+ format(type(d).__name__))
+ if k not in self:
+ self[k] = d
+ return d
+
+ def inverse(self):
+ old = self.copy()
+ self.clear()
+ for k, v in old.items():
+ super(BiDict, self).__setitem__(v, k)