1from collections import Counter
2import random
3
4#disclaimer помагах си с чатбота, но беше доста полезна задача и научих нови неща, въпреки че не е пълна и не работи коректно
5
6class Kid(type):
7 all_children_instances = [] # всички деца от всички класове на метакласа Kid
8 naughty_children = set()
9
10 def __new__(cls, name, bases, dct):
11 if '__call__' not in dct: # Проверяваме дали класът има __call__, само ако има ще го създадем
12 raise NotImplementedError("Children must be callable")
13 new_class = super().__new__(cls, name, bases, dct)
14 return new_class
15
16 def __call__(cls, *args, **kwargs):
17 instance = super().__call__(*args, **kwargs)
18 Kid.all_children_instances.append(instance) #добавяме си новата инстанция към списъка с всички деца
19 instance.is_naughty = False
20 return instance
21
22class Santa:
23 _instance = None
24
25 def __new__(cls): # Създаваме инстанция само ако вече не съществува, така си гарантираме, че класът е singleton
26 if not cls._instance:
27 cls._instance = super(Santa, cls).__new__(cls)
28 cls._instance._init()
29 return cls._instance
30
31 def _init(self):
32 self.requests = {}
33 self.age_counter = Counter()
34
35
36 def xmas(self):
37 naughty_children = self._find_naughty_children()
38 most_wanted_gift = self._most_wanted_gift()
39
40 for child in Kid.all_children_instances:
41 self.age_counter[child] += 1
42 if self.age_counter[child] > 5:
43 continue
44
45 gift = self.requests.get(child, most_wanted_gift)
46 if child in naughty_children:
47 child('coal')
48 elif gift:
49 child(gift)
50
51 self.requests.clear()
52
53 def _find_naughty_children(self):
54 naughty = set()
55 for child in Kid.all_children_instances:
56 for attribute in dir(child): # Проверяваме в класа child за публични методи, които са callable и ще ги добавим в naughty, ако хвярлят грешка
57 if not attribute.startswith('_'):
58 method = getattr(child, attribute)
59 if callable(method):
60 try:
61 method()
62 except Exception:
63 naughty.add(child)
64 child.is_naughty = True
65 break
66 return naughty
67
68 def _most_wanted_gift(self):
69 if not self.requests:
70 return None
71
72 gift_count = {}
73 for gift in self.requests.values():
74 if gift in gift_count:
75 gift_count[gift] += 1
76 else:
77 gift_count[gift] = 1
78
79 max_count = max(gift_count.values())
80 most_common = [gift for gift, count in gift_count.items() if count == max_count]
81
82 if most_common:
83 return random.choice(most_common)
84 return None
85
86 def __iter__(self):
87 return iter(self.requests.values())
..EEEEEEE.EEEEFFEEEE
======================================================================
ERROR: test_call (test.TestSanta.test_call)
Test sending message via calling.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/test.py", line 54, in test_call
self.santa(kid1, "'toy1'")
TypeError: 'Santa' object is not callable
======================================================================
ERROR: test_call_and_mail_same_kid (test.TestSanta.test_call_and_mail_same_kid)
Test that calls and mails work for the same kid.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/test.py", line 69, in test_call_and_mail_same_kid
self.santa(kid1, "'toy1'")
TypeError: 'Santa' object is not callable
======================================================================
ERROR: test_iterable (test.TestSanta.test_iterable)
Ensure Santa can be iterated multiple times including overwriting presents.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/test.py", line 126, in test_iterable
self.santa(kid1, '"something"')
TypeError: 'Santa' object is not callable
======================================================================
ERROR: test_mail (test.TestSanta.test_mail)
Test sending message via email.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/test.py", line 62, in test_mail
self.santa @ f"'toy1'\n{id(kid1)}"
~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~
TypeError: unsupported operand type(s) for @: 'Santa' and 'str'
======================================================================
ERROR: test_present_matching (test.TestSanta.test_present_matching)
Test matching signature in the letter.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/test.py", line 78, in test_present_matching
self.santa @ f"""
TypeError: unsupported operand type(s) for @: 'Santa' and 'str'
======================================================================
ERROR: test_santa_gift_order (test.TestSanta.test_santa_gift_order)
Test ordering of the Santa iterator.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/test.py", line 255, in test_santa_gift_order
self.santa(kid2, '"toy2"')
TypeError: 'Santa' object is not callable
======================================================================
ERROR: test_signature_matching (test.TestSanta.test_signature_matching)
Test matching present in the letter / call.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/test.py", line 100, in test_signature_matching
self.santa @ f"""
TypeError: unsupported operand type(s) for @: 'Santa' and 'str'
======================================================================
ERROR: test_xmass (test.TestSanta.test_xmass)
Test a simple Christmas case.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/test.py", line 137, in test_xmass
self.santa(kid1, '"toy1"')
TypeError: 'Santa' object is not callable
======================================================================
ERROR: test_xmass_kid_with_multiple_wishes (test.TestSanta.test_xmass_kid_with_multiple_wishes)
Test a Christmas with a kid who sends multiple wishes.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/test.py", line 183, in test_xmass_kid_with_multiple_wishes
self.santa(kid1, '"toy1"')
TypeError: 'Santa' object is not callable
======================================================================
ERROR: test_xmass_kid_without_a_wish (test.TestSanta.test_xmass_kid_without_a_wish)
Test a Christmas with a kids that hasn't sent a wish.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/test.py", line 171, in test_xmass_kid_without_a_wish
self.santa(kid1, '"toy1"')
TypeError: 'Santa' object is not callable
======================================================================
ERROR: test_xmass_naughty (test.TestSanta.test_xmass_naughty)
Test a Christmas with naughty kids.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/test.py", line 220, in test_xmass_naughty
self.santa(kid1, "'sirenie'")
TypeError: 'Santa' object is not callable
======================================================================
ERROR: test_xmass_private_with_error (test.TestSanta.test_xmass_private_with_error)
Test a Christmas with not-so-naughty kids.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/test.py", line 234, in test_xmass_private_with_error
self.santa(kid1, "'sirenie'")
TypeError: 'Santa' object is not callable
======================================================================
ERROR: test_xmass_public_with_no_error (test.TestSanta.test_xmass_public_with_no_error)
Test a Christmas with not-so-naughty kids.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/test.py", line 245, in test_xmass_public_with_no_error
self.santa(kid1, "'sirenie'")
TypeError: 'Santa' object is not callable
======================================================================
ERROR: test_xmass_years_5_and_over (test.TestSanta.test_xmass_years_5_and_over)
Test with passing years with kid aged 5 and over.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/test.py", line 211, in test_xmass_years_5_and_over
self.santa(kid1, '"toy"')
TypeError: 'Santa' object is not callable
======================================================================
ERROR: test_xmass_years_under_5 (test.TestSanta.test_xmass_years_under_5)
Test with passing years with a kid under 5 years old.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/test.py", line 192, in test_xmass_years_under_5
self.santa(kid1, '"toy1"')
TypeError: 'Santa' object is not callable
======================================================================
FAIL: test_xmass_no_wishes (test.TestSanta.test_xmass_no_wishes)
Test a Christmas with no wishes.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/test.py", line 151, in test_xmass_no_wishes
self.assertEqual(kid1.SECRET_PRESENT, None)
AssertionError: 'coal' != None
======================================================================
FAIL: test_xmass_no_wishes_but_naughty_kids (test.TestSanta.test_xmass_no_wishes_but_naughty_kids)
Test a Christmas with no wishes, but naughty kids present.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/test.py", line 163, in test_xmass_no_wishes_but_naughty_kids
self.assertEqual(kid1.SECRET_PRESENT, None)
AssertionError: 'coal' != None
----------------------------------------------------------------------
Ran 20 tests in 0.024s
FAILED (failures=2, errors=15)
19.12.2024 15:51
19.12.2024 15:51
19.12.2024 15:52
19.12.2024 15:53
19.12.2024 15:54
19.12.2024 15:55
19.12.2024 15:56