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

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

10 точки общо

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

  1import re
  2from collections import defaultdict
  3import random
  4
  5
  6class Santa:
  7    _santa_the_one_and_only = None
  8    _kids_and_wishes = {}
  9    _kid_christmas_count = defaultdict(int)
 10
 11    def __new__(cls, *args, **kwargs):
 12        if cls._santa_the_one_and_only is None:
 13            cls._santa_the_one_and_only = super(Santa, cls).__new__(cls)
 14        return cls._santa_the_one_and_only
 15
 16    def __call__(self, kid, wish):
 17        gift = self._get_wanted_gift(wish)
 18        self._kids_and_wishes[kid] = gift
 19
 20    def __matmul__(self, letter):
 21        gift = self._get_wanted_gift(letter)
 22        kid_id = self._get_signature(letter)
 23        kid_id.strip()
 24
 25        for kid in Kid._kids:
 26            if id(kid) == int(kid_id):
 27                self._kids_and_wishes[kid] = gift
 28
 29    def __iter__(self):
 30        return iter(self._kids_and_wishes.values())
 31
 32    @staticmethod
 33    def _get_signature(letter):
 34        signature = re.search(r'^\s*(\d+)\s*$', letter, re.MULTILINE)
 35        if (signature):
 36            return str(signature.group(1))
 37
 38    @staticmethod
 39    def _get_wanted_gift(letter):
 40        wanted_gift = re.search(r'[\'\"]([a-zA-Z0-9\s]+)[\' \"]', letter)
 41        if (wanted_gift):
 42            return str(wanted_gift.group(1))
 43
 44    def _get_most_wanted_gift(self):
 45        count_of_gift = defaultdict(int)
 46
 47        for gift in self._kids_and_wishes.values():
 48            count_of_gift[gift] += 1
 49
 50        max_count = max(count_of_gift.values())
 51
 52        most_wanted_gifts = []
 53        for gift, count in count_of_gift.items():
 54            if (count == max_count):
 55                most_wanted_gifts.append(gift)
 56
 57        return random.choice(most_wanted_gifts)
 58
 59    def xmas(self):
 60        if not self._kids_and_wishes:
 61            for kid in Kid._kids:
 62                self._kid_christmas_count[kid] += 1
 63            return
 64
 65        for kid in Kid._kids:
 66            self._kid_christmas_count[kid] += 1
 67            if (self._kid_christmas_count[kid]) > 5:
 68                continue
 69
 70            if kid._is_naughty:
 71                kid('coal')
 72                kid._is_naughty = False
 73                continue
 74
 75            elif kid in self._kids_and_wishes:
 76                kid(self._kids_and_wishes[kid])
 77
 78            else:
 79                kid(self._get_most_wanted_gift())
 80
 81        self._kids_and_wishes.clear()
 82
 83
 84class Kid(type):
 85    _kids = []
 86
 87    def __new__(cls, name, bases, attr_dict):
 88        if '__call__' not in attr_dict:
 89            raise NotImplementedError('Готиняги')
 90        for name, method in attr_dict.items():
 91            if not name.startswith('__') and callable(method):
 92                attr_dict[name] = cls.check_if_naughty(method)
 93        return super().__new__(cls, name, bases, attr_dict)
 94
 95    def __call__(cls, *args, **kwargs):
 96        instance = super().__call__(*args, **kwargs)
 97        Kid._kids.append(instance)
 98        instance._is_naughty = False
 99        return instance
100    
101    def check_if_naughty(method):
102        def decorator(self, *args, **kwargs):
103            try:
104                return method(self, *args, **kwargs)
105            except Exception:
106                self._is_naughty = True
107                raise
108        return decorator

................F...
======================================================================
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.021s

FAILED (failures=1)

Дискусия
История
Това решение има само една версия.