Домашни > Хелоуин в Припят > Решения > Решението на Мартин Гоцев

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

8 точки общо

10 успешни теста
2 неуспешни теста
Код

  1class Candy:
  2    def __init__(self, mass, uranium):
  3        if not isinstance(mass, (int, float)) or mass <= 0:
  4            raise ValueError("Mass must be a positive number.")
  5        if not isinstance(uranium, (int, float)) or uranium < 0 or uranium > 1:
  6            raise ValueError("Uranium must be a number between 0 and 1.")
  7        
  8        self.mass = mass
  9        self.uranium = uranium
 10
 11    def get_uranium_quantity(self):
 12        return self.mass * self.uranium
 13
 14    def get_mass(self):
 15        return self.mass
 16    
 17class Person:
 18    def __init__(self, position):
 19        if not isinstance(position, tuple) or len(position) != 2 or not all(isinstance(coord, int) for coord in position):
 20            raise ValueError("Position must be a tuple of two integers.")
 21        self.position = position
 22
 23    def get_position(self):
 24        return self.position
 25
 26    def set_position(self, new_position):
 27        if not isinstance(new_position, tuple) or len(new_position) != 2 or not all(isinstance(coord, int) for coord in new_position):
 28            raise ValueError("The new position must be a tuple of two integers.")
 29        self.position = new_position
 30
 31class Kid(Person):
 32    CRITICAL_URANIUM_THRESHOLD = 20  
 33
 34    def __init__(self, position, initiative):
 35        super().__init__(position)
 36        if not isinstance(initiative, int) or initiative < 0:
 37            raise ValueError("Initiative must be a non-negative integer.")
 38        self.initiative = initiative
 39        self.candy_basket = []
 40
 41    def get_initiative(self):
 42        return self.initiative
 43
 44    def add_candy(self, candy):
 45        if not isinstance(candy, Candy):
 46            raise ValueError("You must add an object of class Candy to your basket.")
 47        self.candy_basket.append(candy)
 48
 49    def is_critical(self):
 50        uranium_quantity = sum(candy.get_uranium_quantity() for candy in self.candy_basket)
 51        return uranium_quantity > self.CRITICAL_URANIUM_THRESHOLD
 52    
 53class Host(Person):
 54    def __init__(self, position, candies):
 55        super().__init__(position)
 56        self.candy_basket = [Candy(mass, uranium) for mass, uranium in candies]
 57
 58    def remove_candy(self, select_candy_function):
 59        if not self.candy_basket:
 60            return None
 61        selected_candy = select_candy_function(self.candy_basket)
 62        self.candy_basket.remove(selected_candy)
 63        return selected_candy
 64
 65class FluxCapacitor:
 66    def __init__(self, participants):
 67        self.participants = participants
 68
 69    def get_victim(self):
 70        while True:
 71            # Групиране на децата и домакините
 72            kids = {participant for participant in self.participants if isinstance(participant, Kid)}
 73            hosts = {participant for participant in self.participants if isinstance(participant, Host)}
 74            
 75            # Да се провери дали има достатъчно уран в кошниците на децата
 76            critical_kids = {kid for kid in kids if kid.is_critical()}
 77            
 78            # Ако има критични деца, те стават жертви и играта приключва
 79            if critical_kids:
 80                return critical_kids
 81
 82            # Ако няма критични деца, процесът продължава:
 83            new_participants = set()
 84
 85            for host in hosts:
 86                # Всеки домакин обслужва децата при него
 87                for kid in kids:
 88                    kid_position = kid.get_position()
 89                    host_position = host.get_position()
 90                    distance = abs(kid_position[0] - host_position[0]) + abs(kid_position[1] - host_position[1])
 91                    if distance == 0:
 92                        # Детето е при домакина
 93                        host.remove_candy(kids.remove(kid))
 94                    else:
 95                        # Детето се движи към най-близкия домакин, който още не е навестено
 96                        if not kid_position:
 97                            new_position = host_position
 98                        else:
 99                            if distance < abs(kid_position[0] - host_position[0]) + abs(kid_position[1] - host_position[1]):
100                                new_position = host_position
101                            else:
102                                new_position = kid_position
103
104                        kid.set_position(new_position)
105                        new_participants.add(kid)
106
107            # Обновяване на списъка с участниците
108            self.participants = new_participants.union(hosts)
109
110            # Проверка за края на симулацията
111            if not kids:
112                return None   
113            
114                     
115candy = Candy(20, 0.3)
116person = Person((1, 2))
117kid = Kid((0, 0), 123)
118host = Host((3, 4), [(1, 1.0), (2, 0.5)])
119flux_capacitor = FluxCapacitor({kid, host})

....FF......
======================================================================
FAIL: test_no_candies (test.FluxCapacitorTest)
Test with no candies.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/local/lib/python3.10/dist-packages/timeout_decorator/timeout_decorator.py", line 82, in new_function
return function(*args, **kwargs)
File "/tmp/test.py", line 106, in test_no_candies
self.assertEqual(flux_capacitor.get_victim(), None)
File "/tmp/solution.py", line 99, in get_victim
if distance < abs(kid_position[0] - host_position[0]) + abs(kid_position[1] - host_position[1]):
File "/usr/local/lib/python3.10/dist-packages/timeout_decorator/timeout_decorator.py", line 69, in handler
_raise_exception(timeout_exception, exception_message)
File "/usr/local/lib/python3.10/dist-packages/timeout_decorator/timeout_decorator.py", line 45, in _raise_exception
raise exception()
timeout_decorator.timeout_decorator.TimeoutError: 'Timed Out'

======================================================================
FAIL: test_real_case (test.FluxCapacitorTest)
Test with real case.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/local/lib/python3.10/dist-packages/timeout_decorator/timeout_decorator.py", line 82, in new_function
return function(*args, **kwargs)
File "/tmp/test.py", line 115, in test_real_case
self.assertEqual(FluxCapacitor({kid1, kid2, host1, host2}).get_victim(), {kid1, kid2})
File "/tmp/solution.py", line 104, in get_victim
kid.set_position(new_position)
File "/tmp/solution.py", line 26, in set_position
def set_position(self, new_position):
File "/usr/local/lib/python3.10/dist-packages/timeout_decorator/timeout_decorator.py", line 69, in handler
_raise_exception(timeout_exception, exception_message)
File "/usr/local/lib/python3.10/dist-packages/timeout_decorator/timeout_decorator.py", line 45, in _raise_exception
raise exception()
timeout_decorator.timeout_decorator.TimeoutError: 'Timed Out'

----------------------------------------------------------------------
Ran 12 tests in 0.401s

FAILED (failures=2)

Дискусия
Мартин Гоцев
07.11.2023 11:34

Да разбирам че имам безкраен цикъл
Георги Кунчев
07.11.2023 11:25

Поради проблемите, свързани с безкрайни цикли в някои от тестовете, добавихме подобрение на сайта, така че той вече ще отрази точките на всички останали тестове. Ако имаш безкраен цикъл за някой тест кейс, той ще касае само него и все пак ще получиш точки за остнаалите си тестове.
Георги Кунчев
07.11.2023 10:07

С последната си версия си счупил нещо и сега имаш безкраен цикъл. Това ще накара тестовете ни да зависнат и няма д аимаш точки. Моле погледни с реален случай.
Георги Кунчев
07.11.2023 09:56

Докато коментирах, качи нова версия, така че доста от коментарите ми са долу в историята. Моля погледни ги.
История

f1class Candy:f1class Candy:
2    def __init__(self, mass, uranium):2    def __init__(self, mass, uranium):
3        if not isinstance(mass, (int, float)) or mass <= 0:3        if not isinstance(mass, (int, float)) or mass <= 0:
4            raise ValueError("Mass must be a positive number.")4            raise ValueError("Mass must be a positive number.")
5        if not isinstance(uranium, (int, float)) or uranium < 0 or uranium > 1:5        if not isinstance(uranium, (int, float)) or uranium < 0 or uranium > 1:
6            raise ValueError("Uranium must be a number between 0 and 1.")6            raise ValueError("Uranium must be a number between 0 and 1.")
7        7        
8        self.mass = mass8        self.mass = mass
9        self.uranium = uranium9        self.uranium = uranium
1010
11    def get_uranium_quantity(self):11    def get_uranium_quantity(self):
12        return self.mass * self.uranium12        return self.mass * self.uranium
1313
14    def get_mass(self):14    def get_mass(self):
15        return self.mass15        return self.mass
nn16    
16class Person:17class Person:
17    def __init__(self, position):18    def __init__(self, position):
18        if not isinstance(position, tuple) or len(position) != 2 or not all(isinstance(coord, int) for coord in position):19        if not isinstance(position, tuple) or len(position) != 2 or not all(isinstance(coord, int) for coord in position):
19            raise ValueError("Position must be a tuple of two integers.")20            raise ValueError("Position must be a tuple of two integers.")
20        self.position = position21        self.position = position
2122
22    def get_position(self):23    def get_position(self):
23        return self.position24        return self.position
2425
25    def set_position(self, new_position):26    def set_position(self, new_position):
26        if not isinstance(new_position, tuple) or len(new_position) != 2 or not all(isinstance(coord, int) for coord in new_position):27        if not isinstance(new_position, tuple) or len(new_position) != 2 or not all(isinstance(coord, int) for coord in new_position):
27            raise ValueError("The new position must be a tuple of two integers.")28            raise ValueError("The new position must be a tuple of two integers.")
28        self.position = new_position29        self.position = new_position
nn30 
29class Kid(Person):31class Kid(Person):
nn32    CRITICAL_URANIUM_THRESHOLD = 20  
33 
30    def __init__(self, position, initiative):34    def __init__(self, position, initiative):
31        super().__init__(position)35        super().__init__(position)
32        if not isinstance(initiative, int) or initiative < 0:36        if not isinstance(initiative, int) or initiative < 0:
33            raise ValueError("Initiative must be a non-negative integer.")37            raise ValueError("Initiative must be a non-negative integer.")
34        self.initiative = initiative38        self.initiative = initiative
35        self.candy_basket = []39        self.candy_basket = []
3640
37    def get_initiative(self):41    def get_initiative(self):
38        return self.initiative42        return self.initiative
3943
40    def add_candy(self, candy):44    def add_candy(self, candy):
41        if not isinstance(candy, Candy):45        if not isinstance(candy, Candy):
42            raise ValueError("You must add an object of class Candy to your basket.")46            raise ValueError("You must add an object of class Candy to your basket.")
43        self.candy_basket.append(candy)47        self.candy_basket.append(candy)
4448
45    def is_critical(self):49    def is_critical(self):
46        uranium_quantity = sum(candy.get_uranium_quantity() for candy in self.candy_basket)50        uranium_quantity = sum(candy.get_uranium_quantity() for candy in self.candy_basket)
n47        return uranium_quantity > 20n51        return uranium_quantity > self.CRITICAL_URANIUM_THRESHOLD
52    
48class Host(Person):53class Host(Person):
49    def __init__(self, position, candies):54    def __init__(self, position, candies):
50        super().__init__(position)55        super().__init__(position)
51        self.candy_basket = [Candy(mass, uranium) for mass, uranium in candies]56        self.candy_basket = [Candy(mass, uranium) for mass, uranium in candies]
5257
53    def remove_candy(self, select_candy_function):58    def remove_candy(self, select_candy_function):
54        if not self.candy_basket:59        if not self.candy_basket:
55            return None60            return None
56        selected_candy = select_candy_function(self.candy_basket)61        selected_candy = select_candy_function(self.candy_basket)
57        self.candy_basket.remove(selected_candy)62        self.candy_basket.remove(selected_candy)
58        return selected_candy63        return selected_candy
nn64 
59class FluxCapacitor:65class FluxCapacitor:
60    def __init__(self, participants):66    def __init__(self, participants):
61        self.participants = participants67        self.participants = participants
6268
63    def get_victim(self):69    def get_victim(self):
64        while True:70        while True:
65            # Групиране на децата и домакините71            # Групиране на децата и домакините
66            kids = {participant for participant in self.participants if isinstance(participant, Kid)}72            kids = {participant for participant in self.participants if isinstance(participant, Kid)}
67            hosts = {participant for participant in self.participants if isinstance(participant, Host)}73            hosts = {participant for participant in self.participants if isinstance(participant, Host)}
68            74            
69            # Да се провери дали има достатъчно уран в кошниците на децата75            # Да се провери дали има достатъчно уран в кошниците на децата
70            critical_kids = {kid for kid in kids if kid.is_critical()}76            critical_kids = {kid for kid in kids if kid.is_critical()}
71            77            
72            # Ако има критични деца, те стават жертви и играта приключва78            # Ако има критични деца, те стават жертви и играта приключва
73            if critical_kids:79            if critical_kids:
74                return critical_kids80                return critical_kids
7581
76            # Ако няма критични деца, процесът продължава:82            # Ако няма критични деца, процесът продължава:
77            new_participants = set()83            new_participants = set()
7884
79            for host in hosts:85            for host in hosts:
80                # Всеки домакин обслужва децата при него86                # Всеки домакин обслужва децата при него
81                for kid in kids:87                for kid in kids:
82                    kid_position = kid.get_position()88                    kid_position = kid.get_position()
83                    host_position = host.get_position()89                    host_position = host.get_position()
84                    distance = abs(kid_position[0] - host_position[0]) + abs(kid_position[1] - host_position[1])90                    distance = abs(kid_position[0] - host_position[0]) + abs(kid_position[1] - host_position[1])
85                    if distance == 0:91                    if distance == 0:
86                        # Детето е при домакина92                        # Детето е при домакина
87                        host.remove_candy(kids.remove(kid))93                        host.remove_candy(kids.remove(kid))
88                    else:94                    else:
n89                        # Детето се движи към най-близкия домакин, който още не е навестилоn95                        # Детето се движи към най-близкия домакин, който още не е навестено
90                        if not kid_position:96                        if not kid_position:
91                            new_position = host_position97                            new_position = host_position
92                        else:98                        else:
93                            if distance < abs(kid_position[0] - host_position[0]) + abs(kid_position[1] - host_position[1]):99                            if distance < abs(kid_position[0] - host_position[0]) + abs(kid_position[1] - host_position[1]):
94                                new_position = host_position100                                new_position = host_position
95                            else:101                            else:
n96                                new_position = kid_position                        n102                                new_position = kid_position
103 
97                                kid.set_position(new_position)104                        kid.set_position(new_position)
98                                new_participants.add(kid)105                        new_participants.add(kid)
99106
100            # Обновяване на списъка с участниците107            # Обновяване на списъка с участниците
101            self.participants = new_participants.union(hosts)108            self.participants = new_participants.union(hosts)
102109
103            # Проверка за края на симулацията110            # Проверка за края на симулацията
104            if not kids:111            if not kids:
t105                return None            t112                return None   
113            
114                     
106candy = Candy(20, 0.3)115candy = Candy(20, 0.3)
107person = Person((1, 2))116person = Person((1, 2))
108kid = Kid((0, 0), 123)117kid = Kid((0, 0), 123)
109host = Host((3, 4), [(1, 1.0), (2, 0.5)])118host = Host((3, 4), [(1, 1.0), (2, 0.5)])
110flux_capacitor = FluxCapacitor({kid, host})119flux_capacitor = FluxCapacitor({kid, host})
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op

f1class Candy:f1class Candy:
2    def __init__(self, mass, uranium):2    def __init__(self, mass, uranium):
3        if not isinstance(mass, (int, float)) or mass <= 0:3        if not isinstance(mass, (int, float)) or mass <= 0:
4            raise ValueError("Mass must be a positive number.")4            raise ValueError("Mass must be a positive number.")
5        if not isinstance(uranium, (int, float)) or uranium < 0 or uranium > 1:5        if not isinstance(uranium, (int, float)) or uranium < 0 or uranium > 1:
6            raise ValueError("Uranium must be a number between 0 and 1.")6            raise ValueError("Uranium must be a number between 0 and 1.")
7        7        
8        self.mass = mass8        self.mass = mass
9        self.uranium = uranium9        self.uranium = uranium
1010
11    def get_uranium_quantity(self):11    def get_uranium_quantity(self):
12        return self.mass * self.uranium12        return self.mass * self.uranium
1313
14    def get_mass(self):14    def get_mass(self):
15        return self.mass15        return self.mass
16class Person:16class Person:
17    def __init__(self, position):17    def __init__(self, position):
18        if not isinstance(position, tuple) or len(position) != 2 or not all(isinstance(coord, int) for coord in position):18        if not isinstance(position, tuple) or len(position) != 2 or not all(isinstance(coord, int) for coord in position):
19            raise ValueError("Position must be a tuple of two integers.")19            raise ValueError("Position must be a tuple of two integers.")
20        self.position = position20        self.position = position
2121
22    def get_position(self):22    def get_position(self):
23        return self.position23        return self.position
2424
25    def set_position(self, new_position):25    def set_position(self, new_position):
26        if not isinstance(new_position, tuple) or len(new_position) != 2 or not all(isinstance(coord, int) for coord in new_position):26        if not isinstance(new_position, tuple) or len(new_position) != 2 or not all(isinstance(coord, int) for coord in new_position):
27            raise ValueError("The new position must be a tuple of two integers.")27            raise ValueError("The new position must be a tuple of two integers.")
28        self.position = new_position28        self.position = new_position
29class Kid(Person):29class Kid(Person):
30    def __init__(self, position, initiative):30    def __init__(self, position, initiative):
31        super().__init__(position)31        super().__init__(position)
32        if not isinstance(initiative, int) or initiative < 0:32        if not isinstance(initiative, int) or initiative < 0:
33            raise ValueError("Initiative must be a non-negative integer.")33            raise ValueError("Initiative must be a non-negative integer.")
34        self.initiative = initiative34        self.initiative = initiative
35        self.candy_basket = []35        self.candy_basket = []
3636
37    def get_initiative(self):37    def get_initiative(self):
38        return self.initiative38        return self.initiative
3939
40    def add_candy(self, candy):40    def add_candy(self, candy):
41        if not isinstance(candy, Candy):41        if not isinstance(candy, Candy):
42            raise ValueError("You must add an object of class Candy to your basket.")42            raise ValueError("You must add an object of class Candy to your basket.")
43        self.candy_basket.append(candy)43        self.candy_basket.append(candy)
4444
45    def is_critical(self):45    def is_critical(self):
46        uranium_quantity = sum(candy.get_uranium_quantity() for candy in self.candy_basket)46        uranium_quantity = sum(candy.get_uranium_quantity() for candy in self.candy_basket)
47        return uranium_quantity > 2047        return uranium_quantity > 20
48class Host(Person):48class Host(Person):
49    def __init__(self, position, candies):49    def __init__(self, position, candies):
50        super().__init__(position)50        super().__init__(position)
51        self.candy_basket = [Candy(mass, uranium) for mass, uranium in candies]51        self.candy_basket = [Candy(mass, uranium) for mass, uranium in candies]
5252
53    def remove_candy(self, select_candy_function):53    def remove_candy(self, select_candy_function):
54        if not self.candy_basket:54        if not self.candy_basket:
55            return None55            return None
56        selected_candy = select_candy_function(self.candy_basket)56        selected_candy = select_candy_function(self.candy_basket)
57        self.candy_basket.remove(selected_candy)57        self.candy_basket.remove(selected_candy)
58        return selected_candy58        return selected_candy
59class FluxCapacitor:59class FluxCapacitor:
60    def __init__(self, participants):60    def __init__(self, participants):
61        self.participants = participants61        self.participants = participants
6262
63    def get_victim(self):63    def get_victim(self):
64        while True:64        while True:
65            # Групиране на децата и домакините65            # Групиране на децата и домакините
66            kids = {participant for participant in self.participants if isinstance(participant, Kid)}66            kids = {participant for participant in self.participants if isinstance(participant, Kid)}
67            hosts = {participant for participant in self.participants if isinstance(participant, Host)}67            hosts = {participant for participant in self.participants if isinstance(participant, Host)}
68            68            
69            # Да се провери дали има достатъчно уран в кошниците на децата69            # Да се провери дали има достатъчно уран в кошниците на децата
70            critical_kids = {kid for kid in kids if kid.is_critical()}70            critical_kids = {kid for kid in kids if kid.is_critical()}
71            71            
72            # Ако има критични деца, те стават жертви и играта приключва72            # Ако има критични деца, те стават жертви и играта приключва
73            if critical_kids:73            if critical_kids:
74                return critical_kids74                return critical_kids
7575
76            # Ако няма критични деца, процесът продължава:76            # Ако няма критични деца, процесът продължава:
77            new_participants = set()77            new_participants = set()
7878
79            for host in hosts:79            for host in hosts:
80                # Всеки домакин обслужва децата при него80                # Всеки домакин обслужва децата при него
81                for kid in kids:81                for kid in kids:
82                    kid_position = kid.get_position()82                    kid_position = kid.get_position()
83                    host_position = host.get_position()83                    host_position = host.get_position()
84                    distance = abs(kid_position[0] - host_position[0]) + abs(kid_position[1] - host_position[1])84                    distance = abs(kid_position[0] - host_position[0]) + abs(kid_position[1] - host_position[1])
85                    if distance == 0:85                    if distance == 0:
86                        # Детето е при домакина86                        # Детето е при домакина
87                        host.remove_candy(kids.remove(kid))87                        host.remove_candy(kids.remove(kid))
88                    else:88                    else:
89                        # Детето се движи към най-близкия домакин, който още не е навестило89                        # Детето се движи към най-близкия домакин, който още не е навестило
t90                        new_position = host_position if not kid_position else host_position if distance < abs(kid_position[0] - host_position[0]) + abs(kid_position[1] - host_position[1]) else kid_positiont90                        if not kid_position:
91                            new_position = host_position
92                        else:
93                            if distance < abs(kid_position[0] - host_position[0]) + abs(kid_position[1] - host_position[1]):
94                                new_position = host_position
95                            else:
96                                new_position = kid_position                        
91                        kid.set_position(new_position)97                                kid.set_position(new_position)
92                        new_participants.add(kid)98                                new_participants.add(kid)
9399
94            # Обновяване на списъка с участниците100            # Обновяване на списъка с участниците
95            self.participants = new_participants.union(hosts)101            self.participants = new_participants.union(hosts)
96102
97            # Проверка за края на симулацията103            # Проверка за края на симулацията
98            if not kids:104            if not kids:
99                return None            105                return None            
100candy = Candy(20, 0.3)106candy = Candy(20, 0.3)
101person = Person((1, 2))107person = Person((1, 2))
102kid = Kid((0, 0), 123)108kid = Kid((0, 0), 123)
103host = Host((3, 4), [(1, 1.0), (2, 0.5)])109host = Host((3, 4), [(1, 1.0), (2, 0.5)])
104flux_capacitor = FluxCapacitor({kid, host})110flux_capacitor = FluxCapacitor({kid, host})
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op

f1class Candy:f1class Candy:
n2    def init(self, mass, uranium):n2    def __init__(self, mass, uranium):
3        if not isinstance(mass, (int, float)) or mass <= 0:3        if not isinstance(mass, (int, float)) or mass <= 0:
4            raise ValueError("Mass must be a positive number.")4            raise ValueError("Mass must be a positive number.")
5        if not isinstance(uranium, (int, float)) or uranium < 0 or uranium > 1:5        if not isinstance(uranium, (int, float)) or uranium < 0 or uranium > 1:
6            raise ValueError("Uranium must be a number between 0 and 1.")6            raise ValueError("Uranium must be a number between 0 and 1.")
nn7        
7        self.mass = mass8        self.mass = mass
8        self.uranium = uranium9        self.uranium = uranium
nn10 
9    def get_uranium_quantity(self):11    def get_uranium_quantity(self):
10        return self.mass * self.uranium12        return self.mass * self.uranium
nn13 
11    def get_mass(self):14    def get_mass(self):
12        return self.mass15        return self.mass
13class Person:16class Person:
n14    def init(self, position):n17    def __init__(self, position):
15        if not isinstance(position, tuple) or len(position) != 2 or not all(isinstance(coord, int) for coord in position):18        if not isinstance(position, tuple) or len(position) != 2 or not all(isinstance(coord, int) for coord in position):
16            raise ValueError("Position must be a tuple of two integers.")19            raise ValueError("Position must be a tuple of two integers.")
17        self.position = position20        self.position = position
nn21 
18    def get_position(self):22    def get_position(self):
19        return self.position23        return self.position
nn24 
20    def set_position(self, new_position):25    def set_position(self, new_position):
21        if not isinstance(new_position, tuple) or len(new_position) != 2 or not all(isinstance(coord, int) for coord in new_position):26        if not isinstance(new_position, tuple) or len(new_position) != 2 or not all(isinstance(coord, int) for coord in new_position):
22            raise ValueError("The new position must be a tuple of two integers.")27            raise ValueError("The new position must be a tuple of two integers.")
23        self.position = new_position28        self.position = new_position
24class Kid(Person):29class Kid(Person):
n25    def init(self, position, initiative):n30    def __init__(self, position, initiative):
26        super().init(position)31        super().__init__(position)
27        if not isinstance(initiative, int) or initiative < 0:32        if not isinstance(initiative, int) or initiative < 0:
28            raise ValueError("Initiative must be a non-negative integer.")33            raise ValueError("Initiative must be a non-negative integer.")
29        self.initiative = initiative34        self.initiative = initiative
30        self.candy_basket = []35        self.candy_basket = []
nn36 
31    def get_initiative(self):37    def get_initiative(self):
32        return self.initiative38        return self.initiative
nn39 
33    def add_candy(self, candy):40    def add_candy(self, candy):
34        if not isinstance(candy, Candy):41        if not isinstance(candy, Candy):
35            raise ValueError("You must add an object of class Candy to your basket.")42            raise ValueError("You must add an object of class Candy to your basket.")
36        self.candy_basket.append(candy)43        self.candy_basket.append(candy)
nn44 
37    def is_critical(self):45    def is_critical(self):
38        uranium_quantity = sum(candy.get_uranium_quantity() for candy in self.candy_basket)46        uranium_quantity = sum(candy.get_uranium_quantity() for candy in self.candy_basket)
39        return uranium_quantity > 2047        return uranium_quantity > 20
n40    n
41class Host(Person):48class Host(Person):
n42    def init(self, position, candies):n49    def __init__(self, position, candies):
43        super().init(position)50        super().__init__(position)
44        self.candy_basket = [Candy(mass, uranium) for mass, uranium in candies]51        self.candy_basket = [Candy(mass, uranium) for mass, uranium in candies]
4552
46    def remove_candy(self, select_candy_function):53    def remove_candy(self, select_candy_function):
47        if not self.candy_basket:54        if not self.candy_basket:
48            return None55            return None
49        selected_candy = select_candy_function(self.candy_basket)56        selected_candy = select_candy_function(self.candy_basket)
50        self.candy_basket.remove(selected_candy)57        self.candy_basket.remove(selected_candy)
51        return selected_candy58        return selected_candy
n52    n
53class FluxCapacitor:59class FluxCapacitor:
n54    def init(self, participants):n60    def __init__(self, participants):
55        self.participants = participants61        self.participants = participants
nn62 
56    def get_victim(self):63    def get_victim(self):
57        while True:64        while True:
nn65            # Групиране на децата и домакините
58            kids = {participant for participant in self.participants if isinstance(participant, Kid)}66            kids = {participant for participant in self.participants if isinstance(participant, Kid)}
59            hosts = {participant for participant in self.participants if isinstance(participant, Host)}67            hosts = {participant for participant in self.participants if isinstance(participant, Host)}
nn68            
69            # Да се провери дали има достатъчно уран в кошниците на децата
60            critical_kids = {kid for kid in kids if kid.is_critical()}70            critical_kids = {kid for kid in kids if kid.is_critical()}
nn71            
72            # Ако има критични деца, те стават жертви и играта приключва
61            if critical_kids:73            if critical_kids:
62                return critical_kids74                return critical_kids
nn75 
76            # Ако няма критични деца, процесът продължава:
63            new_participants = set()77            new_participants = set()
nn78 
64            for host in hosts:79            for host in hosts:
nn80                # Всеки домакин обслужва децата при него
65                for kid in kids:81                for kid in kids:
66                    kid_position = kid.get_position()82                    kid_position = kid.get_position()
67                    host_position = host.get_position()83                    host_position = host.get_position()
68                    distance = abs(kid_position[0] - host_position[0]) + abs(kid_position[1] - host_position[1])84                    distance = abs(kid_position[0] - host_position[0]) + abs(kid_position[1] - host_position[1])
69                    if distance == 0:85                    if distance == 0:
nn86                        # Детето е при домакина
70                        host.remove_candy(kids.remove(kid))87                        host.remove_candy(kids.remove(kid))
71                    else:88                    else:
nn89                        # Детето се движи към най-близкия домакин, който още не е навестило
72                        new_position = host_position if not kid_position else host_position if distance < abs(kid_position[0] - host_position[0]) + abs(kid_position[1] - host_position[1]) else kid_position90                        new_position = host_position if not kid_position else host_position if distance < abs(kid_position[0] - host_position[0]) + abs(kid_position[1] - host_position[1]) else kid_position
73                        kid.set_position(new_position)91                        kid.set_position(new_position)
74                        new_participants.add(kid)92                        new_participants.add(kid)
nn93 
94            # Обновяване на списъка с участниците
75            self.participants = new_participants.union(hosts)95            self.participants = new_participants.union(hosts)
nn96 
97            # Проверка за края на симулацията
76            if not kids:98            if not kids:
77                return None            99                return None            
t78 t100candy = Candy(20, 0.3)
101person = Person((1, 2))
102kid = Kid((0, 0), 123)
103host = Host((3, 4), [(1, 1.0), (2, 0.5)])
104flux_capacitor = FluxCapacitor({kid, host})
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op