Димитър обнови решението на 19.04.2012 03:48 (преди над 12 години)
+# solution.py
+
+class BiDict:
+
+ def __init__(self, data):
+ self.keys_dict = {}
+ self.values_dict = {}
+ self.update(data)
+
+ def inverse(self):
+ temp_dict_holder = self.keys_dict
+ self.keys_dict = self.values_dict
+ self.values_dict = temp_dict_holder
+
+ def __repr__(self):
+ return str(self.keys_dict)
+
+ def __getitem__(self, key):
+ return self.keys_dict[key]
+
+ def __setitem__(self, key, value):
+ if key in self.keys_dict:
+ if value in self.values_dict:
+ del self.keys_dict[self.values_dict[value]]
+ del self.values_dict[self.keys_dict[key]]
+ else:
+ if value in self.values_dict:
+ del self.keys_dict[self.values_dict[value]]
+ self.keys_dict[key] = value
+ self.values_dict[value] = key
+
+ def keys(self):
+ return self.keys_dict.keys()
+
+ def values(self):
+ return self.keys_dict.values()
+
+ def pop(self, key):
+ self.values_dict.pop(self.keys_dict.pop(key))
+
+ def copy(self):
+ return BiDict(self.keys_dict)
+
+ def update(self, data):
+ for key, value in data.items():
+ self[key] = value
+
+# sample_tests.py (updated)
+
+import unittest
+from solution import *
+
+class BiDictTestCase(unittest.TestCase):
+ def setUp(self):
+ self.person = BiDict({'name': 'Кънчо', 'age': 18, 'sex': 'M'})
+
+ def test_get_a_key(self):
+ self.assertEqual(self.person['name'], 'Кънчо')
+
+ def test_inverse(self):
+ self.person.inverse()
+ self.assertIn('Кънчо', self.person.keys())
+
+ def test_invalid_value(self):
+ self.assertRaises(TypeError, self.person.update, {'sports': ['boxing',]})
+
+ def test_has_dict_attrs(self):
+ self.assertIn('keys', dir(self.person))
+ self.assertIn('pop', dir(self.person))
+ self.assertIn('copy', dir(self.person))
+
+ def test_insert_existing_key_with_existing_value(self):
+ new_person = self.person.copy()
+ new_person['name'] = 18
+ self.assertIn('name', new_person.keys())
+ self.assertIn(18, new_person.values())
+ self.assertNotIn('age', new_person.keys())
+
+ def test_insert_existing_key_with_none_existing_value(self):
+ new_person = self.person.copy()
+ new_person['name'] = -1
+ self.assertIn('name', new_person.keys())
+ self.assertIn(-1, new_person.values())
+ self.assertNotIn('Кънчо', new_person.values())
+
+ def test_insert_none_existing_key_with_existing_value(self):
+ new_person = self.person.copy()
+ new_person['none'] = 18
+ self.assertIn('none', new_person.keys())
+ self.assertIn(18, new_person.values())
+ self.assertNotIn('age', new_person.keys())
+
+ def test_insert_none_existing_key_with_none_existing_value(self):
+ new_person = self.person.copy()
+ new_person['none'] = -1
+ self.assertIn('none', new_person.keys())
+ self.assertIn(-1, new_person.values())
+ self.assertEquals(len(self.person.keys()) + 1, len(new_person.keys()))
+
+if __name__ == '__main__':
+ unittest.main()
+
+