Виктор обнови решението на 19.04.2012 18:49 (преди над 12 години)
+class BiDict:
+
+ def __init__(self, init_dict):
+ temporary_obverse = dict(init_dict)
+ self._inverse = {obverse_val: obverse_key for obverse_key, obverse_val
+ in temporary_obverse.items()}
+ self._obverse = {inverse_val: inverse_key for inverse_key, inverse_val
+ in self._inverse.items()}
+ self._current = self._obverse
+
+ def __getitem__(self, key):
+ return self._current[key]
+
+ def __setitem__(self, key, value):
+ self._current[key] = value
+ new_bidict = BiDict(self._current)
+ if self._current is self._obverse:
+ self._obverse = new_bidict._obverse
+ self._inverse = new_bidict._inverse
+ else:
+ self._obverse = new_bidict._inverse
+ self._inverse = new_bidict._obverse
+ self._current = new_bidict._current
+
+ def __delitem__(self, key):
+ if self._current is self._obverse:
+ del self._inverse[self._obverse[key]]
+ else:
+ del self._obverse[self._inverse[key]]
+
+ def __repr__(self):
+ return repr(self._current)
+
+ def __str__(self):
+ return str(self._current)
+
+ def __contains__(self, item):
+ return item in self._current
+
+ def __iter__(self):
+ return self._current.__iter__
+
+ def inverse(self):
+ if self._current is self._obverse:
+ self._current = self._inverse
+ else:
+ self._current = self._obverse
+
+ def clear(self):
+ self._obverse.clear()
+ self._inverse.clear()
+
+ def copy(self):
+ return BiDict(self._current)
+
+ def get(key, default=None):
+ return get(self._current, default)
+
+ def items():
+ return self._current.items()
+
+ def keys():
+ return self._current.keys()
+
+ def values():
+ return self._current.values()
+
+ def setdefault(key, default=None):
+ if key not in self._current:
+ if self._current is self._obverse:
+ self._inverse[default] = key
+ else:
+ self._obverse[default] = key
+ return self._current.setdefault(key, default)
+
+ def update(iterable = None, **kwargs):
+ if iterable is not None:
+ self._current.update(iterable, **kwargs)
+ else:
+ self._current.update(**kwargs)
+ new_bidict = BiDict(self._current)
+ if self._current is self._obverse:
+ self._obverse = new_bidict._obverse
+ self._inverse = new_bidict._inverse
+ else:
+ self._obverse = new_bidict._inverse
+ self._inverse = new_bidict._obverse
+ self._current = new_bidict._current
+
+ def pop(key, default=None):
+ if key in self._current:
+ if self._current is self._obverse:
+ del self._inverse[self._obverse[key]]
+ else:
+ del self._obverse[self._inverse[key]]
+ return self._current.pop
+
+ def popitem():
+ popped = self._current.popitem()
+ if self._current is self._obverse:
+ del self._inverse[self._obverse[popped[1]]
+ else:
+ del self._obverse[self._inverse[popped[1]]]
+ return popped
+
+ @classmethod
+ def fromkeys(seq, value=None):
+ return BiDict(dict.fromkeys(seq, value))
На реда:
del self._inverse[self._obverse[popped[1]]
Трябва да има още една квадратна скоба. Изял съм я при копирането. :)
П.С. Говоря за 6-7 ред преди края, ред от метода popitem().