Домашни > Another brick in the wall > Решения > Решението на Ева Банова

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

5 точки общо

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

  1class  Material:
  2    def __init__(self, mass, density):
  3        self.mass = mass
  4        self.density = density
  5        self._volume = self.mass / self.density
  6        self._valid = True
  7
  8    def validate(self):
  9         self._valid = False
 10
 11    @property
 12    def volume(self):
 13        return self._volume
 14  
 15
 16class Concrete(Material):
 17    def __init__(self, mass):
 18       super().__init__(mass, 2500)
 19
 20    def __str__(self):
 21        return "Concrete"
 22
 23
 24class Brick(Material):
 25    def __init__(self, mass):
 26       super().__init__(mass, 2000)
 27
 28    def __str__(self):
 29        return "Brick"
 30
 31
 32class Stone(Material):
 33    def __init__(self, mass):
 34       super().__init__(mass, 1600)
 35
 36    def __str__(self):
 37        return "Stone"
 38
 39
 40class Wood(Material):
 41    def __init__(self, mass):
 42       super().__init__(mass, 600)
 43
 44    def __str__(self):
 45        return "Wood"
 46
 47
 48class Steel(Material):
 49    def __init__(self, mass):
 50       super().__init__(mass, 7700)
 51
 52    def __str__(self):
 53        return "Steel"
 54
 55
 56materials = {"Concrete" : Concrete, "Brick" : Brick, "Stone" : Stone, "Wood" : Wood, "Steel" : Steel}
 57
 58
 59class Factory:
 60    _instances = []
 61
 62    def __init__(self):
 63        self._total_volume = 0
 64        self._materials = []
 65        Factory._instances.append(self)
 66
 67    def __call__(self, *args, **kwargs):
 68        if bool(args) == bool(kwargs):
 69            raise ValueError("greshkaaaa soriii")
 70        if bool(kwargs):
 71            result = []
 72            for key, value in kwargs.items():
 73                if key not in materials:
 74                    raise ValueError("greshkaaaa soriii")
 75                current = materials[key](value)
 76                if current._valid:
 77                    self._total_volume += current.volume
 78                result.append(current)
 79                self._materials.extend(result)
 80            return tuple(result)
 81        if bool(args):
 82            mass = 0
 83            density = 0
 84            count = []
 85            number = 1
 86            names = []
 87            for material in args:
 88                if not material._valid:
 89                    raise AssertionError("greshkaaaa soriii")
 90                material.validate()
 91                mass += material.mass
 92                density += material.density
 93                names.append(str(material))
 94                self._total_volume += material.volume
 95            for met, val in materials.items():
 96                counter = 0
 97                for material in args:
 98                    if met in str(material) and met != str(material):
 99                        counter += 1
100                count.append(counter)
101            for c in count:
102                if c != 0:
103                    number = 0
104                    break
105            for c in count:
106                if c != 0:
107                    number += 1
108            names = sorted(names)
109            class_name = "_".join(names)
110            if class_name in materials:
111                Fusion = materials[class_name]
112            else:
113                Fusion = type(class_name, (Material,), 
114                              {"__init__": lambda self, *_args, **kwargs: Material.__init__(self, mass, density / number)})
115                materials[class_name] = Fusion
116            fused_material = Fusion(mass)
117            self._materials.append(fused_material)
118            return Fusion()
119            
120    def can_build(self, needed_volume):
121        return self._total_volume >= needed_volume 
122
123    @classmethod
124    def can_build_together(cls, needed_volume):
125         total_volume = sum(mat.volume for inst in cls._instances for mat in inst._materials if mat._valid)
126         return total_volume >= needed_volume 

.FE..FFE..
======================================================================
ERROR: test_materials_between_factories (test.TestFactory.test_materials_between_factories)
Test materials sharing.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/test.py", line 160, in test_materials_between_factories
self.factory1(wood)
File "/tmp/solution.py", line 118, in __call__
return Fusion()
^^^^^^^^
TypeError: Wood.__init__() missing 1 required positional argument: 'mass'

======================================================================
ERROR: test_positional_arguments_single_argument (test.TestFactory.test_positional_arguments_single_argument)
Test calling a factory using a sigle positional argument.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/test.py", line 79, in test_positional_arguments_single_argument
concrete2 = self.factory1(concrete1)
^^^^^^^^^^^^^^^^^^^^^^^^
File "/tmp/solution.py", line 118, in __call__
return Fusion()
^^^^^^^^
TypeError: Concrete.__init__() missing 1 required positional argument: 'mass'

======================================================================
FAIL: test_can_build (test.TestFactory.test_can_build)
Test can_build methods.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/test.py", line 175, in test_can_build
self.assertFalse(self.factory2.can_build(4.0001))
AssertionError: True is not false

======================================================================
FAIL: test_positional_arguments_multiple_argument_from_initial_set (test.TestFactory.test_positional_arguments_multiple_argument_from_initial_set)
Test calling a factory using multiple positional arguments.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/test.py", line 95, in test_positional_arguments_multiple_argument_from_initial_set
self.assertEqual(result.volume, 6.0) # Density=1700, mass=10200
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: 2.0 != 6.0

======================================================================
FAIL: test_positional_arguments_multiple_argument_with_dynamics (test.TestFactory.test_positional_arguments_multiple_argument_with_dynamics)
Test calling a factory using multiple positional arguments.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/test.py", line 125, in test_positional_arguments_multiple_argument_with_dynamics
self.assertAlmostEqual(brick_concrete_stone.volume, 5.2131, places=4)
AssertionError: 1.7377049180327868 != 5.2131 within 4 places (3.4753950819672133 difference)

----------------------------------------------------------------------
Ran 10 tests in 0.018s

FAILED (failures=3, errors=2)

Дискусия
Ева Банова
26.11.2024 17:25

Имам проблем с пресмятането на total volume във функциите can_build can_build_together. От няколко час се опитвам да го оправя, ама не става та го качвам така :-)
История
Това решение има само една версия.