Домашни > Работилница за отвари! > Решения > Решението на Теодор Вълчев

Резултати
6 точки от тестове
0 точки от учител

6 точки общо

11 успешни теста
9 неуспешни теста
Код
Скрий всички коментари

  1# this is test-version while travelling with train, it's very bumpy and hard to see the programs :D :D, code is  not tested
  2# TODO improvements: make private effects and duration, refactor code duplication,
  3#  abstract access through getters/ setters, use function style not for loop
  4class Potion:
  5    def __init__(self, effects_a, duration):
  6        self.effects = effects_a
  7        self.intensity_effects_tracker = dict()
  8        self.is_part_of_something_bigger = False
  9        self.used_effects_tracker = set()
 10        self.depleted_string = "Effect is depleted."
 11
 12        for key, value in effects_a.items():
 13            self.intensity_effects_tracker[key] = 1
 14
 15        for key, value in effects_a.items():
 16            self.__setattr__(key, effects_a[key])
 17        self.duration = duration
 18        self.used = False
 19
 20    def __getattribute__(self, name):
 21        if name in ["effects"]:
 22            return object.__getattribute__(self, name)
 23        elif name in self.effects.keys() and name in self.used_effects_tracker:
 24            raise TypeError(self.depleted_string)
 25        elif name in self.effects.keys():
 26            if self.is_part_of_something_bigger:
 27                raise TypeError("Potion is now part of something bigger than itself.")
 28
 29            def multy_magic(target_a):
 30                for x in range(0, self.intensity_effects_tracker[name], 1):
 31                    self.effects[name](target_a)
 32            self.used_effects_tracker.add(name)
 33            return multy_magic
 34        return object.__getattribute__(self, name)
 35
 36    def __add__(self, other):
 37        self.is_part_of_something_bigger = True
 38        sum_intensity_effects_tracker = dict()
 39        sum_effects = self.effects | other.effects
 40
 41        for effect_name in sum_effects.keys():
 42            if effect_name in self.effects.keys() and effect_name in other.effects.keys():
 43                sum_intensity_effects_tracker[effect_name] = (self.intensity_effects_tracker[effect_name] +
 44                                                              other.intensity_effects_tracker[effect_name])
 45            else:
 46                if effect_name in self.effects.keys():
 47                    sum_intensity_effects_tracker[effect_name] = self.intensity_effects_tracker[effect_name]
 48                else:
 49                    sum_intensity_effects_tracker[effect_name] = other.intensity_effects_tracker[effect_name]
 50
 51        sum_duration = max(self.duration, other.duration)
 52        sum_potion = Potion(sum_effects, sum_duration)
 53        sum_potion.intensity_effects_tracker = sum_intensity_effects_tracker
 54        return sum_potion
 55
 56    def __mul__(self, coefficient):
 57        self.is_part_of_something_bigger = True
 58        if coefficient > 1:
 59            potentiated = self
 60            for x in range(0, coefficient - 1, 1):
 61                potentiated = potentiated + self
 62            return potentiated
 63        else:
 64            for effect in self.effects.keys():
 65                self.intensity_effects_tracker[effect] = round(self.intensity_effects_tracker[effect] * coefficient)
 66
 67    def __sub__(self, other):
 68        self.is_part_of_something_bigger = True
 69        if len(set(other.effects.keys()) - set(self.effects.keys())) > 0:
 70            raise TypeError("Test, Test Presidential alert: Tova e test: Opaa shte umrem bate, "
 71                            "tazi rakiq e dignala mnogo gradus. "
 72                            "Da ne se preporuchva na deca pod 12 godini za 8-mi dekemvri.")
 73        result_potion = Potion({}, self.duration)
 74        for name in self.effects.keys():
 75            if name not in other.effects.keys():
 76                result_potion.intensity_effects_tracker[name] = self.intensity_effects_tracker[name]
 77                result_potion.effects[name] = self.effects[name]
 78                result_potion.__setattr__(name, self.effects[name])
 79            else:
 80                if other.intensity_effects_tracker[name] < self.intensity_effects_tracker[name]:
 81                    result_potion.intensity_effects_tracker[name] = self.intensity_effects_tracker[name] - \
 82                                                                    other.intensity_effects_tracker[name]
 83                    result_potion.effects[name] = other.effects[name]
 84                    result_potion.__setattr__(name, other.effects[name])
 85        return result_potion
 86
 87    def __truediv__(self, n):
 88        self.is_part_of_something_bigger = True
 89        result_potion = Potion(self.effects, self.duration)
 90        for key, value in self.intensity_effects_tracker.items():
 91            result_potion.intensity_effects_tracker[key] = round(value / n)
 92        return (result_potion,)*n
 93
 94    def __eq__(self, other):
 95        if len(set(self.effects.keys()).difference(set(other.effects.keys()))) > 0:
 96            return False
 97        for key, value in self.intensity_effects_tracker.items():
 98            if value != other.intensity_effects_tracker[key]:
 99                return False
100        return True
101
102    def __gt__(self, other):
103        self_intensity_sum = 0
104        for _, value in self.intensity_effects_tracker.items():
105            self_intensity_sum += value
106        other_intensity_sum = 0
107        for _, value in other.intensity_effects_tracker.items():
108            other_intensity_sum += value
109        if self_intensity_sum > other_intensity_sum:
110            return True
111        return False
112
113
114class ГоспожатаПоХимия:
115    def __init__(self):
116        self.ticker = 0
117        self.students_in_gas_chamber = dict()
118
119    def apply(self, target_a, potion):
120        if potion.used:
121            raise TypeError("Potion is depleted.")
122        if potion.is_part_of_something_bigger:
123            raise TypeError("Potion is now part of something bigger than itself.")
124        applicable = dict()
125        for key in potion.effects.keys():
126            if key not in potion.used_effects_tracker:
127                applicable[sum(map(ord, key))] = key
128        if len(applicable) > 0:
129            target_with_head_dict = target_a.__dict__.copy()
130            if self.ticker in self.students_in_gas_chamber.keys():
131                self.students_in_gas_chamber[self.ticker + potion.duration] = (
132                    self.students_in_gas_chamber[self.ticker].append((target_a, target_with_head_dict)))
133            else:
134                self.students_in_gas_chamber[self.ticker + potion.duration] = [(target_a, target_with_head_dict)]
135            for index in sorted(applicable, reverse=True):
136                potion.effects[applicable[index]](target_a)
137            potion.depleted_string = "Potion is depleted."
138
139    def tick(self):
140        self.ticker += 1
141        if self.ticker in self.students_in_gas_chamber.keys():
142            for target_student, previous_head in self.students_in_gas_chamber[self.ticker]:
143                target_student.__dict__ = previous_head

...F...FE..EF...FFFF
======================================================================
ERROR: test_dilution (test.TestPotionOperations)
Test dilution of a potion.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/test.py", line 119, in test_dilution
half_potion.int_attr_fun(self._target)
AttributeError: 'NoneType' object has no attribute 'int_attr_fun'

======================================================================
ERROR: test_separation (test.TestPotionOperations)
Test separation of a potion.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/test.py", line 218, in test_separation
potion2.int_attr_fun(self._target)
File "/tmp/solution.py", line 24, in __getattribute__
raise TypeError(self.depleted_string)
TypeError: Effect is depleted.

======================================================================
FAIL: test_equal (test.TestPotionComparison)
Test equality of potions.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/test.py", line 304, in test_equal
self.assertNotEqual(potion1, potion2)
AssertionError: <solution.Potion object at 0x7fab72adb730> == <solution.Potion object at 0x7fab72adba90>

======================================================================
FAIL: test_deprecation (test.TestPotionOperations)
Test deprecation of a potion.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/test.py", line 259, in test_deprecation
with self.assertRaisesRegex(TypeError, 'Potion is now part of something bigger than itself\.'):
AssertionError: TypeError not raised

======================================================================
FAIL: test_applying_depleted_potion (test.TestГоспожатаПоХимия)
Test applying a depleted potion or a potion that was used in a reaction.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/test.py", line 380, in test_applying_depleted_potion
with self.assertRaisesRegex(TypeError, 'Potion is depleted\.'):
AssertionError: TypeError not raised

======================================================================
FAIL: test_ticking_immutable (test.TestГоспожатаПоХимия)
Test ticking after applying a potion with immutable attributes.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/test.py", line 425, in test_ticking_immutable
self.assertEqual(self._target.int_attr, 500)
AssertionError: 50 != 500

======================================================================
FAIL: test_ticking_multiple_potions (test.TestГоспожатаПоХимия)
Test ticking after applying multiple potions which affect the same attribute.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/test.py", line 458, in test_ticking_multiple_potions
self.assertEqual(self._target.int_attr, 50)
AssertionError: 5 != 50

======================================================================
FAIL: test_ticking_multiple_targets (test.TestГоспожатаПоХимия)
Test ticking after applying a potion with mutable attributes.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/test.py", line 487, in test_ticking_multiple_targets
self.assertEqual(target1.int_attr, 500)
AssertionError: 50 != 500

======================================================================
FAIL: test_ticking_mutable (test.TestГоспожатаПоХимия)
Test ticking after applying a potion with mutable attributes.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/test.py", line 446, in test_ticking_mutable
self.assertEqual(self._target.list_attr, [1, 2, 3])
AssertionError: Lists differ: [1, 2, 3, 4] != [1, 2, 3]

First list contains 1 additional elements.
First extra element 3:
4

- [1, 2, 3, 4]
? ---

+ [1, 2, 3]

----------------------------------------------------------------------
Ran 20 tests in 0.003s

FAILED (failures=7, errors=2)

Дискусия
Теодор Вълчев
05.12.2023 00:20

мда, просто магистър, работа, пътуване, исках да пренапиша, но It's what It's :D :D хаха. благодаря много за обратната връзка!
Виктор Бечев
04.12.2023 14:21

Казал си. :grin:
Теодор Вълчев
04.12.2023 10:33

Като гледам, май нямам много време да пренапиша за втора версия 😂.
Виктор Бечев
03.12.2023 13:46

`# this is test-version while travelling with train, it's very bumpy and hard to see the programs :D :D, code is not tested` Тогава за да не ти давам обратна връзка за код, който мислиш да преработиш - на следващата версия. :D
История

f1# this is test-version while travelling with train, it's very bumpy and hard to see the programs :D :D, code is  not testedf1# this is test-version while travelling with train, it's very bumpy and hard to see the programs :D :D, code is  not tested
2# TODO improvements: make private effects and duration, refactor code duplication,2# TODO improvements: make private effects and duration, refactor code duplication,
3#  abstract access through getters/ setters, use function style not for loop3#  abstract access through getters/ setters, use function style not for loop
4class Potion:4class Potion:
5    def __init__(self, effects_a, duration):5    def __init__(self, effects_a, duration):
6        self.effects = effects_a6        self.effects = effects_a
7        self.intensity_effects_tracker = dict()7        self.intensity_effects_tracker = dict()
n8        self.isPartOfSomethingBigger = Falsen8        self.is_part_of_something_bigger = False
9        self.used_effects_tracker = set()9        self.used_effects_tracker = set()
10        self.depleted_string = "Effect is depleted."10        self.depleted_string = "Effect is depleted."
1111
12        for key, value in effects_a.items():12        for key, value in effects_a.items():
13            self.intensity_effects_tracker[key] = 113            self.intensity_effects_tracker[key] = 1
1414
15        for key, value in effects_a.items():15        for key, value in effects_a.items():
16            self.__setattr__(key, effects_a[key])16            self.__setattr__(key, effects_a[key])
17        self.duration = duration17        self.duration = duration
18        self.used = False18        self.used = False
1919
20    def __getattribute__(self, name):20    def __getattribute__(self, name):
21        if name in ["effects"]:21        if name in ["effects"]:
22            return object.__getattribute__(self, name)22            return object.__getattribute__(self, name)
23        elif name in self.effects.keys() and name in self.used_effects_tracker:23        elif name in self.effects.keys() and name in self.used_effects_tracker:
24            raise TypeError(self.depleted_string)24            raise TypeError(self.depleted_string)
25        elif name in self.effects.keys():25        elif name in self.effects.keys():
n26            if self.isPartOfSomethingBigger:n26            if self.is_part_of_something_bigger:
27                raise TypeError("Potion is now part of something bigger than itself.")27                raise TypeError("Potion is now part of something bigger than itself.")
2828
29            def multy_magic(target_a):29            def multy_magic(target_a):
30                for x in range(0, self.intensity_effects_tracker[name], 1):30                for x in range(0, self.intensity_effects_tracker[name], 1):
31                    self.effects[name](target_a)31                    self.effects[name](target_a)
32            self.used_effects_tracker.add(name)32            self.used_effects_tracker.add(name)
33            return multy_magic33            return multy_magic
34        return object.__getattribute__(self, name)34        return object.__getattribute__(self, name)
3535
36    def __add__(self, other):36    def __add__(self, other):
n37        self.isPartOfSomethingBigger = Truen37        self.is_part_of_something_bigger = True
38        sum_intensity_effects_tracker = dict()38        sum_intensity_effects_tracker = dict()
39        sum_effects = self.effects | other.effects39        sum_effects = self.effects | other.effects
4040
41        for effect_name in sum_effects.keys():41        for effect_name in sum_effects.keys():
42            if effect_name in self.effects.keys() and effect_name in other.effects.keys():42            if effect_name in self.effects.keys() and effect_name in other.effects.keys():
43                sum_intensity_effects_tracker[effect_name] = (self.intensity_effects_tracker[effect_name] +43                sum_intensity_effects_tracker[effect_name] = (self.intensity_effects_tracker[effect_name] +
44                                                              other.intensity_effects_tracker[effect_name])44                                                              other.intensity_effects_tracker[effect_name])
45            else:45            else:
46                if effect_name in self.effects.keys():46                if effect_name in self.effects.keys():
47                    sum_intensity_effects_tracker[effect_name] = self.intensity_effects_tracker[effect_name]47                    sum_intensity_effects_tracker[effect_name] = self.intensity_effects_tracker[effect_name]
48                else:48                else:
49                    sum_intensity_effects_tracker[effect_name] = other.intensity_effects_tracker[effect_name]49                    sum_intensity_effects_tracker[effect_name] = other.intensity_effects_tracker[effect_name]
5050
51        sum_duration = max(self.duration, other.duration)51        sum_duration = max(self.duration, other.duration)
52        sum_potion = Potion(sum_effects, sum_duration)52        sum_potion = Potion(sum_effects, sum_duration)
53        sum_potion.intensity_effects_tracker = sum_intensity_effects_tracker53        sum_potion.intensity_effects_tracker = sum_intensity_effects_tracker
54        return sum_potion54        return sum_potion
5555
56    def __mul__(self, coefficient):56    def __mul__(self, coefficient):
n57        self.isPartOfSomethingBigger = Truen57        self.is_part_of_something_bigger = True
58        if coefficient > 1:58        if coefficient > 1:
59            potentiated = self59            potentiated = self
60            for x in range(0, coefficient - 1, 1):60            for x in range(0, coefficient - 1, 1):
61                potentiated = potentiated + self61                potentiated = potentiated + self
62            return potentiated62            return potentiated
63        else:63        else:
64            for effect in self.effects.keys():64            for effect in self.effects.keys():
65                self.intensity_effects_tracker[effect] = round(self.intensity_effects_tracker[effect] * coefficient)65                self.intensity_effects_tracker[effect] = round(self.intensity_effects_tracker[effect] * coefficient)
6666
67    def __sub__(self, other):67    def __sub__(self, other):
n68        self.isPartOfSomethingBigger = Truen68        self.is_part_of_something_bigger = True
69        if len(set(other.effects.keys()) - set(self.effects.keys())) > 0:69        if len(set(other.effects.keys()) - set(self.effects.keys())) > 0:
70            raise TypeError("Test, Test Presidential alert: Tova e test: Opaa shte umrem bate, "70            raise TypeError("Test, Test Presidential alert: Tova e test: Opaa shte umrem bate, "
71                            "tazi rakiq e dignala mnogo gradus. "71                            "tazi rakiq e dignala mnogo gradus. "
72                            "Da ne se preporuchva na deca pod 12 godini za 8-mi dekemvri.")72                            "Da ne se preporuchva na deca pod 12 godini za 8-mi dekemvri.")
73        result_potion = Potion({}, self.duration)73        result_potion = Potion({}, self.duration)
74        for name in self.effects.keys():74        for name in self.effects.keys():
75            if name not in other.effects.keys():75            if name not in other.effects.keys():
76                result_potion.intensity_effects_tracker[name] = self.intensity_effects_tracker[name]76                result_potion.intensity_effects_tracker[name] = self.intensity_effects_tracker[name]
77                result_potion.effects[name] = self.effects[name]77                result_potion.effects[name] = self.effects[name]
78                result_potion.__setattr__(name, self.effects[name])78                result_potion.__setattr__(name, self.effects[name])
79            else:79            else:
80                if other.intensity_effects_tracker[name] < self.intensity_effects_tracker[name]:80                if other.intensity_effects_tracker[name] < self.intensity_effects_tracker[name]:
81                    result_potion.intensity_effects_tracker[name] = self.intensity_effects_tracker[name] - \81                    result_potion.intensity_effects_tracker[name] = self.intensity_effects_tracker[name] - \
82                                                                    other.intensity_effects_tracker[name]82                                                                    other.intensity_effects_tracker[name]
83                    result_potion.effects[name] = other.effects[name]83                    result_potion.effects[name] = other.effects[name]
84                    result_potion.__setattr__(name, other.effects[name])84                    result_potion.__setattr__(name, other.effects[name])
85        return result_potion85        return result_potion
8686
87    def __truediv__(self, n):87    def __truediv__(self, n):
n88        self.isPartOfSomethingBigger = Truen88        self.is_part_of_something_bigger = True
89        result_potion = Potion(self.effects, self.duration)89        result_potion = Potion(self.effects, self.duration)
90        for key, value in self.intensity_effects_tracker.items():90        for key, value in self.intensity_effects_tracker.items():
91            result_potion.intensity_effects_tracker[key] = round(value / n)91            result_potion.intensity_effects_tracker[key] = round(value / n)
92        return (result_potion,)*n92        return (result_potion,)*n
9393
94    def __eq__(self, other):94    def __eq__(self, other):
95        if len(set(self.effects.keys()).difference(set(other.effects.keys()))) > 0:95        if len(set(self.effects.keys()).difference(set(other.effects.keys()))) > 0:
96            return False96            return False
97        for key, value in self.intensity_effects_tracker.items():97        for key, value in self.intensity_effects_tracker.items():
98            if value != other.intensity_effects_tracker[key]:98            if value != other.intensity_effects_tracker[key]:
99                return False99                return False
100        return True100        return True
101101
102    def __gt__(self, other):102    def __gt__(self, other):
103        self_intensity_sum = 0103        self_intensity_sum = 0
104        for _, value in self.intensity_effects_tracker.items():104        for _, value in self.intensity_effects_tracker.items():
105            self_intensity_sum += value105            self_intensity_sum += value
106        other_intensity_sum = 0106        other_intensity_sum = 0
107        for _, value in other.intensity_effects_tracker.items():107        for _, value in other.intensity_effects_tracker.items():
108            other_intensity_sum += value108            other_intensity_sum += value
109        if self_intensity_sum > other_intensity_sum:109        if self_intensity_sum > other_intensity_sum:
110            return True110            return True
111        return False111        return False
112112
113113
114class ГоспожатаПоХимия:114class ГоспожатаПоХимия:
115    def __init__(self):115    def __init__(self):
116        self.ticker = 0116        self.ticker = 0
117        self.students_in_gas_chamber = dict()117        self.students_in_gas_chamber = dict()
118118
119    def apply(self, target_a, potion):119    def apply(self, target_a, potion):
120        if potion.used:120        if potion.used:
121            raise TypeError("Potion is depleted.")121            raise TypeError("Potion is depleted.")
t122        if potion.isPartOfSomethingBigger:t122        if potion.is_part_of_something_bigger:
123            raise TypeError("Potion is now part of something bigger than itself.")123            raise TypeError("Potion is now part of something bigger than itself.")
124        applicable = dict()124        applicable = dict()
125        for key in potion.effects.keys():125        for key in potion.effects.keys():
126            if key not in potion.used_effects_tracker:126            if key not in potion.used_effects_tracker:
127                applicable[sum(map(ord, key))] = key127                applicable[sum(map(ord, key))] = key
128        if len(applicable) > 0:128        if len(applicable) > 0:
129            target_with_head_dict = target_a.__dict__.copy()129            target_with_head_dict = target_a.__dict__.copy()
130            if self.ticker in self.students_in_gas_chamber.keys():130            if self.ticker in self.students_in_gas_chamber.keys():
131                self.students_in_gas_chamber[self.ticker + potion.duration] = (131                self.students_in_gas_chamber[self.ticker + potion.duration] = (
132                    self.students_in_gas_chamber[self.ticker].append((target_a, target_with_head_dict)))132                    self.students_in_gas_chamber[self.ticker].append((target_a, target_with_head_dict)))
133            else:133            else:
134                self.students_in_gas_chamber[self.ticker + potion.duration] = [(target_a, target_with_head_dict)]134                self.students_in_gas_chamber[self.ticker + potion.duration] = [(target_a, target_with_head_dict)]
135            for index in sorted(applicable, reverse=True):135            for index in sorted(applicable, reverse=True):
136                potion.effects[applicable[index]](target_a)136                potion.effects[applicable[index]](target_a)
137            potion.depleted_string = "Potion is depleted."137            potion.depleted_string = "Potion is depleted."
138138
139    def tick(self):139    def tick(self):
140        self.ticker += 1140        self.ticker += 1
141        if self.ticker in self.students_in_gas_chamber.keys():141        if self.ticker in self.students_in_gas_chamber.keys():
142            for target_student, previous_head in self.students_in_gas_chamber[self.ticker]:142            for target_student, previous_head in self.students_in_gas_chamber[self.ticker]:
143                target_student.__dict__ = previous_head143                target_student.__dict__ = previous_head
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op