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

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

9 точки общо

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

  1import re
  2
  3class Santa:
  4    _instance = None
  5    _all_gifts_and_counts = {}
  6    _all_kids_and_ages = {}
  7    _all_kids_and_gifts = {}
  8
  9    def __new__(cls):
 10        if not cls._instance:
 11            cls._instance = super(Santa, cls).__new__(cls)
 12        return cls._instance
 13
 14    def __iter__(self):
 15        return iter(self._all_kids_and_gifts.values())
 16
 17    def __call__(self, kid, wish):
 18        gift = self.get_gift(wish)
 19        self._all_kids_and_gifts[kid] = gift
 20
 21    def __matmul__(self, letter):
 22        match = re.search(r'^\s*(\d+)\s*$', letter, re.MULTILINE)
 23        signature = int(match.group(1))
 24        gift = self.get_gift(letter)
 25
 26        for kid in Kid.all_kids:
 27            if id(kid) == signature:
 28                self._all_kids_and_gifts[kid] = gift
 29
 30    def get_gift(self, letter):
 31        match = re.search(r'["\']([a-zA-Z0-9 ]+)["\']', letter)
 32        gift = match.group(1)
 33
 34        if gift not in self._all_gifts_and_counts:
 35            self._all_gifts_and_counts[gift] = 1
 36        else:
 37            self._all_gifts_and_counts[gift] += 1
 38
 39        return gift
 40
 41    def add_kids_ages(self, kid):
 42        if kid not in self._all_kids_and_ages:
 43            self._all_kids_and_ages[kid] = 0
 44        else:
 45            self._all_kids_and_ages[kid] += 1
 46
 47    def xmas(self):
 48        if not self._all_gifts_and_counts:
 49            for kid in Kid.all_kids:
 50                self.add_kids_ages(kid)
 51            print("Никой не получава нищо, защото няма желания")
 52            return
 53
 54        most_wished = max(self._all_gifts_and_counts, key=self._all_gifts_and_counts.get)
 55
 56        for kid in Kid.all_kids:
 57            self.add_kids_ages(kid)
 58
 59            if self._all_kids_and_ages[kid] > 5:
 60                continue
 61
 62            if getattr(kid, "is_naughty", False):
 63                kid("coal")
 64                kid.is_naughty = False
 65                print(f"{id(kid)} получава coal")
 66            else:
 67                gift = self._all_kids_and_gifts.get(kid)
 68                if gift:
 69                    kid(gift)
 70                    print(f"{id(kid)} получава {gift}")
 71                else:
 72                    kid(most_wished)
 73                    print(f"{id(kid)} получава {most_wished}")
 74
 75        self._all_gifts_and_counts.clear()
 76
 77def is_kid_bad(method):
 78    def wrapped(self, *args, **kwargs):
 79        try:
 80            return method(self, *args, **kwargs)
 81        except Exception:
 82            self.is_naughty = True
 83            raise
 84    return wrapped
 85
 86class Kid(type):
 87    all_kids = set()
 88    def __new__(cls, name, bases, attr_dict):
 89
 90        for key, value in attr_dict.items():
 91            if hasattr(value, "__call__") and not key.startswith("_"):
 92                attr_dict[key] = is_kid_bad(value)
 93
 94        return super().__new__(cls, name, bases, attr_dict)
 95
 96    def __call__(cls, *args, **kwargs):
 97        instance = super().__call__(*args, **kwargs)
 98        Kid.all_kids.add(instance)
 99        instance.is_naughty = False
100        if not callable(instance):
101            raise NotImplementedError("Сори, няма да има подарък.")
102        return instance

.F................F
Stdout:
Никой не получава нищо, защото няма желания
Никой не получава нищо, защото няма желания
Никой не получава нищо, защото няма желания
Никой не получава нищо, защото няма желания
Никой не получава нищо, защото няма желания
136176170527456 получава toy
.
======================================================================
FAIL: test_class_from_kid_without_call_dunder (test.TestKid.test_class_from_kid_without_call_dunder)
Test creating new class from Kid.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/test.py", line 18, in test_class_from_kid_without_call_dunder
with self.assertRaises(NotImplementedError):
AssertionError: NotImplementedError not raised

======================================================================
FAIL: 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 213, in test_xmass_years_5_and_over
self.assertEqual(kid1.SECRET_PRESENT, None)
AssertionError: 'toy' != None

Stdout:
Никой не получава нищо, защото няма желания
Никой не получава нищо, защото няма желания
Никой не получава нищо, защото няма желания
Никой не получава нищо, защото няма желания
Никой не получава нищо, защото няма желания
136176170527456 получава toy

----------------------------------------------------------------------
Ran 20 tests in 0.059s

FAILED (failures=2)

Дискусия
История

t1import ret1import re
22
3class Santa:3class Santa:
4    _instance = None4    _instance = None
5    _all_gifts_and_counts = {}5    _all_gifts_and_counts = {}
6    _all_kids_and_ages = {}6    _all_kids_and_ages = {}
7    _all_kids_and_gifts = {}7    _all_kids_and_gifts = {}
88
9    def __new__(cls):9    def __new__(cls):
10        if not cls._instance:10        if not cls._instance:
11            cls._instance = super(Santa, cls).__new__(cls)11            cls._instance = super(Santa, cls).__new__(cls)
12        return cls._instance12        return cls._instance
1313
14    def __iter__(self):14    def __iter__(self):
15        return iter(self._all_kids_and_gifts.values())15        return iter(self._all_kids_and_gifts.values())
1616
17    def __call__(self, kid, wish):17    def __call__(self, kid, wish):
18        gift = self.get_gift(wish)18        gift = self.get_gift(wish)
19        self._all_kids_and_gifts[kid] = gift19        self._all_kids_and_gifts[kid] = gift
2020
21    def __matmul__(self, letter):21    def __matmul__(self, letter):
22        match = re.search(r'^\s*(\d+)\s*$', letter, re.MULTILINE)22        match = re.search(r'^\s*(\d+)\s*$', letter, re.MULTILINE)
23        signature = int(match.group(1))23        signature = int(match.group(1))
24        gift = self.get_gift(letter)24        gift = self.get_gift(letter)
2525
26        for kid in Kid.all_kids:26        for kid in Kid.all_kids:
27            if id(kid) == signature:27            if id(kid) == signature:
28                self._all_kids_and_gifts[kid] = gift28                self._all_kids_and_gifts[kid] = gift
2929
30    def get_gift(self, letter):30    def get_gift(self, letter):
31        match = re.search(r'["\']([a-zA-Z0-9 ]+)["\']', letter)31        match = re.search(r'["\']([a-zA-Z0-9 ]+)["\']', letter)
32        gift = match.group(1)32        gift = match.group(1)
3333
34        if gift not in self._all_gifts_and_counts:34        if gift not in self._all_gifts_and_counts:
35            self._all_gifts_and_counts[gift] = 135            self._all_gifts_and_counts[gift] = 1
36        else:36        else:
37            self._all_gifts_and_counts[gift] += 137            self._all_gifts_and_counts[gift] += 1
3838
39        return gift39        return gift
4040
41    def add_kids_ages(self, kid):41    def add_kids_ages(self, kid):
42        if kid not in self._all_kids_and_ages:42        if kid not in self._all_kids_and_ages:
43            self._all_kids_and_ages[kid] = 043            self._all_kids_and_ages[kid] = 0
44        else:44        else:
45            self._all_kids_and_ages[kid] += 145            self._all_kids_and_ages[kid] += 1
4646
47    def xmas(self):47    def xmas(self):
48        if not self._all_gifts_and_counts:48        if not self._all_gifts_and_counts:
49            for kid in Kid.all_kids:49            for kid in Kid.all_kids:
50                self.add_kids_ages(kid)50                self.add_kids_ages(kid)
51            print("Никой не получава нищо, защото няма желания")51            print("Никой не получава нищо, защото няма желания")
52            return52            return
5353
54        most_wished = max(self._all_gifts_and_counts, key=self._all_gifts_and_counts.get)54        most_wished = max(self._all_gifts_and_counts, key=self._all_gifts_and_counts.get)
5555
56        for kid in Kid.all_kids:56        for kid in Kid.all_kids:
57            self.add_kids_ages(kid)57            self.add_kids_ages(kid)
5858
59            if self._all_kids_and_ages[kid] > 5:59            if self._all_kids_and_ages[kid] > 5:
60                continue60                continue
6161
62            if getattr(kid, "is_naughty", False):62            if getattr(kid, "is_naughty", False):
63                kid("coal")63                kid("coal")
64                kid.is_naughty = False64                kid.is_naughty = False
65                print(f"{id(kid)} получава coal")65                print(f"{id(kid)} получава coal")
66            else:66            else:
67                gift = self._all_kids_and_gifts.get(kid)67                gift = self._all_kids_and_gifts.get(kid)
68                if gift:68                if gift:
69                    kid(gift)69                    kid(gift)
70                    print(f"{id(kid)} получава {gift}")70                    print(f"{id(kid)} получава {gift}")
71                else:71                else:
72                    kid(most_wished)72                    kid(most_wished)
73                    print(f"{id(kid)} получава {most_wished}")73                    print(f"{id(kid)} получава {most_wished}")
7474
75        self._all_gifts_and_counts.clear()75        self._all_gifts_and_counts.clear()
7676
77def is_kid_bad(method):77def is_kid_bad(method):
78    def wrapped(self, *args, **kwargs):78    def wrapped(self, *args, **kwargs):
79        try:79        try:
80            return method(self, *args, **kwargs)80            return method(self, *args, **kwargs)
81        except Exception:81        except Exception:
82            self.is_naughty = True82            self.is_naughty = True
83            raise83            raise
84    return wrapped84    return wrapped
8585
86class Kid(type):86class Kid(type):
87    all_kids = set()87    all_kids = set()
88    def __new__(cls, name, bases, attr_dict):88    def __new__(cls, name, bases, attr_dict):
8989
90        for key, value in attr_dict.items():90        for key, value in attr_dict.items():
91            if hasattr(value, "__call__") and not key.startswith("_"):91            if hasattr(value, "__call__") and not key.startswith("_"):
92                attr_dict[key] = is_kid_bad(value)92                attr_dict[key] = is_kid_bad(value)
9393
94        return super().__new__(cls, name, bases, attr_dict)94        return super().__new__(cls, name, bases, attr_dict)
9595
96    def __call__(cls, *args, **kwargs):96    def __call__(cls, *args, **kwargs):
97        instance = super().__call__(*args, **kwargs)97        instance = super().__call__(*args, **kwargs)
98        Kid.all_kids.add(instance)98        Kid.all_kids.add(instance)
99        instance.is_naughty = False99        instance.is_naughty = False
100        if not callable(instance):100        if not callable(instance):
101            raise NotImplementedError("Сори, няма да има подарък.")101            raise NotImplementedError("Сори, няма да има подарък.")
102        return instance102        return instance
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op