Домашни > Подаръци ще има за всички от сърце > Решения > Решението на Станислава Желязкова

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

7 точки общо

13 успешни теста
7 неуспешни теста
Код

 1import re
 2from collections import Counter
 3
 4exception_found = False
 5MAX_NUMBER_OF_YEARS = 5 
 6kids_info = {}
 7
 8def catch_exceptions(func):
 9    def wrapper(*args, **kwargs):
10        global exception_found
11        try:
12            return func(*args, **kwargs)
13        except Exception as e:
14            exception_found = True  
15    return wrapper
16
17
18class Santa:
19    _instance = None  
20    def __new__(cls, *args, **kwargs):
21        if cls._instance is None:
22            cls._instance = super().__new__(cls)
23            cls._instance._wishes = []
24            cls._instance._wish_counter = Counter()  
25        return cls._instance
26    
27    def __call__(self, child, wish):
28        wish_match = re.search(r'"([a-zA-Z0-9][a-zA-Z0-9\s]*[a-zA-Z0-9])"|\'([a-zA-Z0-9][a-zA-Z0-9\s]*[a-zA-Z0-9])\'', wish)
29        gift = wish_match.group(1) or wish_match.group(2)
30        self._wishes.append(gift)
31        child_id = id(child)
32        self._wish_counter[gift]+=1
33        kids_info[child_id]['wishes'].append(gift)
34    
35    def __matmul__(self, letter):
36        if not isinstance(letter, str):
37            raise ValueError("Невалидно писмо!")
38        id_match = re.search(r'\s*(\d+)\s*$', letter,re.MULTILINE)
39        kid_id = int(id_match.group(1))
40        wish_match = re.search(r'"([a-zA-Z0-9][a-zA-Z0-9\s]*[a-zA-Z0-9])"|\'([a-zA-Z0-9][a-zA-Z0-9\s]*[a-zA-Z0-9])\'', letter)
41        if wish_match:
42            gift = wish_match.group(1) if wish_match.group(1) else wish_match.group(2)
43            self._wishes.append(gift)
44            self._wish_counter[gift]+=1
45            kids_info[kid_id]['wishes'].append(gift)
46
47    def __iter__(self):
48        for wish in self._wishes:
49                yield wish
50
51    def xmas(self):
52        if not self._wishes:
53            for child_id, info in list(kids_info.items()):
54                info['year_count'] += 1
55            print("Никой не получава нищо, защото няма желания")
56            return
57        global exception_found
58        most_common_gift = self._wish_counter.most_common(1)[0][0]
59
60        for child_id, info in list(kids_info.items()):
61            child=info['child'] 
62            if info['year_count'] >= MAX_NUMBER_OF_YEARS:
63                del kids_info[child_id]
64                continue
65            gift = info['wishes'][-1] if info['wishes'] else most_common_gift
66            if exception_found:
67                gift = 'coal'
68            info['year_count'] += 1
69            child(gift)
70            exception_found = False
71        
72        for kid_id, kid_data in kids_info.items():
73            kid_data['wishes'].clear()
74        self._wishes.clear()
75        self._wish_counter.clear()
76
77        
78class Kid(type):
79    def __new__(cls, name, bases, dct):
80        if '__call__' not in dct: 
81            raise NotImplementedError( "Всеки клас, който използва Kid трябва да имплементира __call__! " )
82        for attr_name,attr_value in dct.items():
83            if callable(attr_value):
84                dct[attr_name]=catch_exceptions(attr_value)
85        return super().__new__(cls, name, bases, dct)
86    
87    def __call__(cls, *args, **kwargs):
88        instance = super().__call__(*args, **kwargs)
89        kids_info[id(instance)] = {'child':instance,'wishes': [], 'year_count': 0}
90        return instance 
91    

...FF.FFE....F..F...
======================================================================
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 106, in test_signature_matching
self.santa @ f"""
File "/tmp/solution.py", line 45, in __matmul__
kids_info[kid_id]['wishes'].append(gift)
~~~~~~~~~^^^^^^^^
KeyError: 12345678

======================================================================
FAIL: 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 71, in test_call_and_mail_same_kid
self.assertEqual(list(self.santa), ['toy1'])
AssertionError: Lists differ: ['toy1', 'toy1'] != ['toy1']

First list contains 1 additional elements.
First extra element 1:
'toy1'

- ['toy1', 'toy1']
+ ['toy1']

======================================================================
FAIL: 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 129, in test_iterable
self.assertEqual(list(self.santa), ['something', 'something else'])
AssertionError: Lists differ: ['something', 'something not used', 'something else'] != ['something', 'something else']

First differing element 1:
'something not used'
'something else'

First list contains 1 additional elements.
First extra element 2:
'something else'

- ['something', 'something not used', 'something else']
+ ['something', 'something else']

======================================================================
FAIL: test_present_matching (test.TestSanta.test_present_matching)
Test matching signature in the letter.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/test.py", line 92, in test_present_matching
self.assertEqual(list(self.santa), ['toy4', 'abcdefgHIJKLMNopQRstUVwxYZ 1 2 3 4567890 '])
AssertionError: Lists differ: ['toy4'] != ['toy4', 'abcdefgHIJKLMNopQRstUVwxYZ 1 2 3 4567890 ']

Second list contains 1 additional elements.
First extra element 1:
'abcdefgHIJKLMNopQRstUVwxYZ 1 2 3 4567890 '

- ['toy4']
+ ['toy4', 'abcdefgHIJKLMNopQRstUVwxYZ 1 2 3 4567890 ']

======================================================================
FAIL: 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 260, in test_santa_gift_order
self.assertEqual(list(self.santa), ["toy2v2", "toy3", "toy1"])
AssertionError: Lists differ: ['toy2', 'toy3', 'toy1', 'toy2v2'] != ['toy2v2', 'toy3', 'toy1']

First differing element 0:
'toy2'
'toy2v2'

First list contains 1 additional elements.
First extra element 3:
'toy2v2'

- ['toy2', 'toy3', 'toy1', 'toy2v2']
+ ['toy2v2', 'toy3', 'toy1']

======================================================================
FAIL: test_xmass_naughty (test.TestSanta.test_xmass_naughty)
Test a Christmas with naughty kids.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/test.py", line 222, in test_xmass_naughty
with self.assertRaises(ZeroDivisionError):
AssertionError: ZeroDivisionError not raised

======================================================================
FAIL: 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 240, in test_xmass_private_with_error
self.assertEqual(kid1.SECRET_PRESENT, 'sirenie')
AssertionError: 'coal' != 'sirenie'
- coal
+ sirenie

----------------------------------------------------------------------
Ran 20 tests in 0.055s

FAILED (failures=6, errors=1)

Дискусия
Георги Кунчев
18.12.2024 12:55

Оставяй по два празни реда между класовете си (и като цяло между код на топ-левел).
История

f1import ref1import re
2from collections import Counter2from collections import Counter
33
n4exception_found=Falsen4exception_found = False
5MAX_NUMBER_OF_YEARS = 5 
5kids_info={}6kids_info = {}
67
7def catch_exceptions(func):8def catch_exceptions(func):
n8    def wrapper(*args,**kwargs):n9    def wrapper(*args, **kwargs):
9        global exception_found10        global exception_found
10        try:11        try:
n11            return func(*args,**kwargs)n12            return func(*args, **kwargs)
12        except Exception as e:13        except Exception as e:
n13            exception_found=True  n14            exception_found = True  
14    return wrapper15    return wrapper
nn16 
1517
16class Santa:18class Santa:
17    _instance = None  19    _instance = None  
18    def __new__(cls, *args, **kwargs):20    def __new__(cls, *args, **kwargs):
19        if cls._instance is None:21        if cls._instance is None:
20            cls._instance = super().__new__(cls)22            cls._instance = super().__new__(cls)
n21            cls._instance._wishes =[]n23            cls._instance._wishes = []
22            cls._instance._wish_counter=Counter()  24            cls._instance._wish_counter = Counter()  
23        return cls._instance25        return cls._instance
24    26    
n25    def __call__(self,child,wish):n27    def __call__(self, child, wish):
26        wish_match= re.search(r'"([a-zA-Z0-9][a-zA-Z0-9\s]*[a-zA-Z0-9])"|\'([a-zA-Z0-9][a-zA-Z0-9\s]*[a-zA-Z0-9])\'', wish)28        wish_match = re.search(r'"([a-zA-Z0-9][a-zA-Z0-9\s]*[a-zA-Z0-9])"|\'([a-zA-Z0-9][a-zA-Z0-9\s]*[a-zA-Z0-9])\'', wish)
27        gift = wish_match.group(1) or wish_match.group(2)29        gift = wish_match.group(1) or wish_match.group(2)
28        self._wishes.append(gift)30        self._wishes.append(gift)
n29        child_id=id(child)n31        child_id = id(child)
30        self._wish_counter[gift]+=132        self._wish_counter[gift]+=1
31        kids_info[child_id]['wishes'].append(gift)33        kids_info[child_id]['wishes'].append(gift)
32    34    
n33    def __matmul__(self,letter):n35    def __matmul__(self, letter):
34        if not isinstance(letter, str):36        if not isinstance(letter, str):
35            raise ValueError("Невалидно писмо!")37            raise ValueError("Невалидно писмо!")
n36        id_match=re.search(r'\s*(\d+)\s*$', letter,re.MULTILINE)n38        id_match = re.search(r'\s*(\d+)\s*$', letter,re.MULTILINE)
37        kid_id = int(id_match.group(1))39        kid_id = int(id_match.group(1))
n38        wish_match=re.search(r'"([a-zA-Z0-9][a-zA-Z0-9\s]*[a-zA-Z0-9])"|\'([a-zA-Z0-9][a-zA-Z0-9\s]*[a-zA-Z0-9])\'', letter)n40        wish_match = re.search(r'"([a-zA-Z0-9][a-zA-Z0-9\s]*[a-zA-Z0-9])"|\'([a-zA-Z0-9][a-zA-Z0-9\s]*[a-zA-Z0-9])\'', letter)
39        if wish_match:41        if wish_match:
40            gift = wish_match.group(1) if wish_match.group(1) else wish_match.group(2)42            gift = wish_match.group(1) if wish_match.group(1) else wish_match.group(2)
41            self._wishes.append(gift)43            self._wishes.append(gift)
42            self._wish_counter[gift]+=144            self._wish_counter[gift]+=1
43            kids_info[kid_id]['wishes'].append(gift)45            kids_info[kid_id]['wishes'].append(gift)
4446
45    def __iter__(self):47    def __iter__(self):
n46        for wishes in self._wishes:n48        for wish in self._wishes:
47                yield wishes49                yield wish
4850
49    def xmas(self):51    def xmas(self):
50        if not self._wishes:52        if not self._wishes:
51            for child_id, info in list(kids_info.items()):53            for child_id, info in list(kids_info.items()):
52                info['year_count'] += 154                info['year_count'] += 1
53            print("Никой не получава нищо, защото няма желания")55            print("Никой не получава нищо, защото няма желания")
54            return56            return
55        global exception_found57        global exception_found
n56        most_common_gift=self._wish_counter.most_common(1)[0][0]n58        most_common_gift = self._wish_counter.most_common(1)[0][0]
57        59 
58        for child_id, info in list(kids_info.items()):60        for child_id, info in list(kids_info.items()):
59            child=info['child'] 61            child=info['child'] 
n60            if info['year_count']>=5:n62            if info['year_count'] >= MAX_NUMBER_OF_YEARS:
61                del kids_info[child_id]63                del kids_info[child_id]
62                continue64                continue
63            gift = info['wishes'][-1] if info['wishes'] else most_common_gift65            gift = info['wishes'][-1] if info['wishes'] else most_common_gift
64            if exception_found:66            if exception_found:
65                gift = 'coal'67                gift = 'coal'
66            info['year_count'] += 168            info['year_count'] += 1
67            child(gift)69            child(gift)
n68            exception_found=Falsen70            exception_found = False
69        71        
70        for kid_id, kid_data in kids_info.items():72        for kid_id, kid_data in kids_info.items():
71            kid_data['wishes'].clear()73            kid_data['wishes'].clear()
72        self._wishes.clear()74        self._wishes.clear()
73        self._wish_counter.clear()75        self._wish_counter.clear()
7476
75        77        
76class Kid(type):78class Kid(type):
77    def __new__(cls, name, bases, dct):79    def __new__(cls, name, bases, dct):
78        if '__call__' not in dct: 80        if '__call__' not in dct: 
79            raise NotImplementedError( "Всеки клас, който използва Kid трябва да имплементира __call__! " )81            raise NotImplementedError( "Всеки клас, който използва Kid трябва да имплементира __call__! " )
80        for attr_name,attr_value in dct.items():82        for attr_name,attr_value in dct.items():
81            if callable(attr_value):83            if callable(attr_value):
82                dct[attr_name]=catch_exceptions(attr_value)84                dct[attr_name]=catch_exceptions(attr_value)
83        return super().__new__(cls, name, bases, dct)85        return super().__new__(cls, name, bases, dct)
84    86    
85    def __call__(cls, *args, **kwargs):87    def __call__(cls, *args, **kwargs):
86        instance = super().__call__(*args, **kwargs)88        instance = super().__call__(*args, **kwargs)
87        kids_info[id(instance)] = {'child':instance,'wishes': [], 'year_count': 0}89        kids_info[id(instance)] = {'child':instance,'wishes': [], 'year_count': 0}
88        return instance 90        return instance 
89    91    
t90class BulgarianKid(metaclass=Kid):t
91    def __call__(self,present):
92        print(f"Получава {present}")
93        return "Йейй!"
94    
95    def be_naughty(self):
96        raise RuntimeError('Не си изядох зеленчуците!')
97    
98class ChineseKid(metaclass=Kid):
99 
100    def __call__(self, present):
101        print(f"Получава {present}")
102        return "Ураа!"
103 
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op

f1import ref1import re
2from collections import Counter2from collections import Counter
33
4exception_found=False4exception_found=False
5kids_info={}5kids_info={}
66
7def catch_exceptions(func):7def catch_exceptions(func):
8    def wrapper(*args,**kwargs):8    def wrapper(*args,**kwargs):
9        global exception_found9        global exception_found
10        try:10        try:
11            return func(*args,**kwargs)11            return func(*args,**kwargs)
12        except Exception as e:12        except Exception as e:
n13            exception_found=Truen13            exception_found=True  
14        
15    return wrapper14    return wrapper
1615
17class Santa:16class Santa:
18    _instance = None  17    _instance = None  
n19 n
20    def __new__(cls, *args, **kwargs):18    def __new__(cls, *args, **kwargs):
21        if cls._instance is None:19        if cls._instance is None:
22            cls._instance = super().__new__(cls)20            cls._instance = super().__new__(cls)
23            cls._instance._wishes =[]21            cls._instance._wishes =[]
24            cls._instance._wish_counter=Counter()  22            cls._instance._wish_counter=Counter()  
25        return cls._instance23        return cls._instance
26    24    
27    def __call__(self,child,wish):25    def __call__(self,child,wish):
28        wish_match= re.search(r'"([a-zA-Z0-9][a-zA-Z0-9\s]*[a-zA-Z0-9])"|\'([a-zA-Z0-9][a-zA-Z0-9\s]*[a-zA-Z0-9])\'', wish)26        wish_match= re.search(r'"([a-zA-Z0-9][a-zA-Z0-9\s]*[a-zA-Z0-9])"|\'([a-zA-Z0-9][a-zA-Z0-9\s]*[a-zA-Z0-9])\'', wish)
29        gift = wish_match.group(1) or wish_match.group(2)27        gift = wish_match.group(1) or wish_match.group(2)
30        self._wishes.append(gift)28        self._wishes.append(gift)
31        child_id=id(child)29        child_id=id(child)
32        self._wish_counter[gift]+=130        self._wish_counter[gift]+=1
33        kids_info[child_id]['wishes'].append(gift)31        kids_info[child_id]['wishes'].append(gift)
34    32    
35    def __matmul__(self,letter):33    def __matmul__(self,letter):
36        if not isinstance(letter, str):34        if not isinstance(letter, str):
37            raise ValueError("Невалидно писмо!")35            raise ValueError("Невалидно писмо!")
38        id_match=re.search(r'\s*(\d+)\s*$', letter,re.MULTILINE)36        id_match=re.search(r'\s*(\d+)\s*$', letter,re.MULTILINE)
39        kid_id = int(id_match.group(1))37        kid_id = int(id_match.group(1))
40        wish_match=re.search(r'"([a-zA-Z0-9][a-zA-Z0-9\s]*[a-zA-Z0-9])"|\'([a-zA-Z0-9][a-zA-Z0-9\s]*[a-zA-Z0-9])\'', letter)38        wish_match=re.search(r'"([a-zA-Z0-9][a-zA-Z0-9\s]*[a-zA-Z0-9])"|\'([a-zA-Z0-9][a-zA-Z0-9\s]*[a-zA-Z0-9])\'', letter)
41        if wish_match:39        if wish_match:
42            gift = wish_match.group(1) if wish_match.group(1) else wish_match.group(2)40            gift = wish_match.group(1) if wish_match.group(1) else wish_match.group(2)
43            self._wishes.append(gift)41            self._wishes.append(gift)
44            self._wish_counter[gift]+=142            self._wish_counter[gift]+=1
45            kids_info[kid_id]['wishes'].append(gift)43            kids_info[kid_id]['wishes'].append(gift)
4644
47    def __iter__(self):45    def __iter__(self):
48        for wishes in self._wishes:46        for wishes in self._wishes:
49                yield wishes47                yield wishes
5048
51    def xmas(self):49    def xmas(self):
52        if not self._wishes:50        if not self._wishes:
53            for child_id, info in list(kids_info.items()):51            for child_id, info in list(kids_info.items()):
54                info['year_count'] += 152                info['year_count'] += 1
55            print("Никой не получава нищо, защото няма желания")53            print("Никой не получава нищо, защото няма желания")
56            return54            return
57        global exception_found55        global exception_found
58        most_common_gift=self._wish_counter.most_common(1)[0][0]56        most_common_gift=self._wish_counter.most_common(1)[0][0]
t59 t57        
60        for child_id, info in list(kids_info.items()):58        for child_id, info in list(kids_info.items()):
61            child=info['child'] 59            child=info['child'] 
62            if info['year_count']>=5:60            if info['year_count']>=5:
63                del kids_info[child_id]61                del kids_info[child_id]
64                continue62                continue
65            gift = info['wishes'][-1] if info['wishes'] else most_common_gift63            gift = info['wishes'][-1] if info['wishes'] else most_common_gift
66            if exception_found:64            if exception_found:
67                gift = 'coal'65                gift = 'coal'
68            info['year_count'] += 166            info['year_count'] += 1
69            child(gift)67            child(gift)
70            exception_found=False68            exception_found=False
71        69        
72        for kid_id, kid_data in kids_info.items():70        for kid_id, kid_data in kids_info.items():
73            kid_data['wishes'].clear()71            kid_data['wishes'].clear()
74        self._wishes.clear()72        self._wishes.clear()
75        self._wish_counter.clear()73        self._wish_counter.clear()
7674
77        75        
78class Kid(type):76class Kid(type):
79    def __new__(cls, name, bases, dct):77    def __new__(cls, name, bases, dct):
80        if '__call__' not in dct: 78        if '__call__' not in dct: 
81            raise NotImplementedError( "Всеки клас, който използва Kid трябва да имплементира __call__! " )79            raise NotImplementedError( "Всеки клас, който използва Kid трябва да имплементира __call__! " )
82        for attr_name,attr_value in dct.items():80        for attr_name,attr_value in dct.items():
83            if callable(attr_value):81            if callable(attr_value):
84                dct[attr_name]=catch_exceptions(attr_value)82                dct[attr_name]=catch_exceptions(attr_value)
85        return super().__new__(cls, name, bases, dct)83        return super().__new__(cls, name, bases, dct)
86    84    
87    def __call__(cls, *args, **kwargs):85    def __call__(cls, *args, **kwargs):
88        instance = super().__call__(*args, **kwargs)86        instance = super().__call__(*args, **kwargs)
89        kids_info[id(instance)] = {'child':instance,'wishes': [], 'year_count': 0}87        kids_info[id(instance)] = {'child':instance,'wishes': [], 'year_count': 0}
90        return instance 88        return instance 
91    89    
92class BulgarianKid(metaclass=Kid):90class BulgarianKid(metaclass=Kid):
93    def __call__(self,present):91    def __call__(self,present):
94        print(f"Получава {present}")92        print(f"Получава {present}")
95        return "Йейй!"93        return "Йейй!"
96    94    
97    def be_naughty(self):95    def be_naughty(self):
98        raise RuntimeError('Не си изядох зеленчуците!')96        raise RuntimeError('Не си изядох зеленчуците!')
99    97    
100class ChineseKid(metaclass=Kid):98class ChineseKid(metaclass=Kid):
10199
102    def __call__(self, present):100    def __call__(self, present):
103        print(f"Получава {present}")101        print(f"Получава {present}")
104        return "Ураа!"102        return "Ураа!"
105103
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op