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

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

8 точки общо

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

  1import re
  2import random 
  3
  4class Santa:
  5    _instance = None
  6    _kids = []
  7    _presents = {} #dictionary with kid and wish, but only those who wrote a letter or called
  8
  9    def __new__(cls, *args):
 10        """Make Santa singleton."""
 11        if cls._instance is None:
 12            cls._instance = super().__new__(cls)
 13        return cls._instance
 14
 15    def _kid_exists(self, kid_id):
 16        """Check if a kid exists by ID."""
 17        existing_kid = None
 18        for kid in self._kids:
 19            if id(kid) == kid_id or kid.id == kid_id:
 20                existing_kid = kid
 21                break
 22        return existing_kid
 23    
 24    def __call__(self, kid, message):
 25        """Process a kid's wish from a phone call."""
 26        present = self._extract_wish_from_message(message)
 27        existing_kid = self._kid_exists(id(kid))
 28        if existing_kid:            
 29            self._presents[existing_kid] = present
 30        else:
 31            self._presents[kid] = present
 32
 33    def __matmul__(self, letter):
 34        """Process a kid's wish from a letter."""
 35        present = self._extract_wish_from_message(letter)
 36        kid_id = self._extract_id_from_message(letter)
 37        existing_kid = self._kid_exists(kid_id)
 38        if existing_kid:            
 39            self._presents[existing_kid] = present
 40        else:
 41            new_kid_class_by_ID = Kid.__new__(Kid, f"Kid_{kid_id}", (object,), {
 42                "id": kid_id, 
 43                "age": 0, 
 44                "name": f"Kid_{kid_id}",
 45                "__call__": lambda self, present: None
 46                })
 47            kid_by_ID = new_kid_class_by_ID()
 48            self._presents[kid_by_ID] = present
 49
 50    def _extract_id_from_message(self, message):
 51        """Extract kid ID from a message."""
 52        id_pattern  =  r'^\s*(\d+)\s*$'
 53        kid_id_match = re.search(id_pattern, message, re.MULTILINE)
 54        return int(kid_id_match.group(1)) if kid_id_match else None
 55
 56    def _extract_wish_from_message(self, message):
 57        """Extract a wish from a message."""
 58        wish_pattern = r'["\']([A-Za-z0-9 ]+)["\']'
 59        wish_match = re.search(wish_pattern, message)
 60        return  wish_match.group(1) if wish_match else None
 61    
 62    def __iter__(self):
 63        """Iterate over presents."""
 64        for key in self._presents:
 65            yield self._presents[key]
 66
 67    def find_most_wanted_present(self):
 68        """Find the most wanted present."""
 69        if not self._presents:
 70            return None
 71
 72        wish_counter = {}
 73        for wish in self._presents.values():
 74            if wish in wish_counter:
 75                wish_counter[wish] += 1
 76            else:
 77                wish_counter[wish] = 1
 78
 79        max_count = max(wish_counter.values())
 80        most_wanted_presents = [wish for wish,count in wish_counter.items() if count == max_count]
 81
 82        return random.choice(most_wanted_presents) 
 83
 84    def xmas(self):
 85        """Deliver presents to kids."""
 86        if not self._presents:
 87            print("Дядо Коледа не е получил желания, отива да се депресира") 
 88            return
 89
 90        most_wanted_present = self.find_most_wanted_present()
 91
 92        for kid in self._kids:
 93            kid.age += 1
 94
 95            if kid.age > 5 :
 96                print(f"{kid.name} is too old for presents.") 
 97                continue
 98  
 99            else: 
100                if kid in self._presents and self._presents[kid]:
101                    present = self._presents[kid]
102                    kid(present)
103                    print(f"{kid.name} received {present}")
104                else:
105                    kid(most_wanted_present)
106                    print(f"{kid.name} received most wanted {most_wanted_present}")
107        
108        self._presents = {}  #clear presents for next year
109     
110
111class Kid(type):
112    def __new__(cls, name, bases, attr_dict):
113        attr_dict['id'] = 0
114        attr_dict['age'] = 0
115        attr_dict['name'] = name #if we don't name the kid
116        attr_dict['__init__'] = lambda self: Santa._instance._kids.append(self)
117        if "__call__" not in attr_dict:
118            raise NotImplementedError("mnogo se oburkah")
119        return super().__new__(cls, name, bases, attr_dict)

.............F
Stdout:
KidClass1 received sirenie
KidClass1 received sirenie
KidClass2 received most wanted sirenie
E
Stdout:
Дядо Коледа не е получил желания, отива да се депресира
E
Stdout:
Дядо Коледа не е получил желания, отива да се депресира
..F
Stdout:
Дядо Коледа не е получил желания, отива да се депресира
Дядо Коледа не е получил желания, отива да се депресира
Дядо Коледа не е получил желания, отива да се депресира
Дядо Коледа не е получил желания, отива да се депресира
Дядо Коледа не е получил желания, отива да се депресира
KidClass1 received toy
.
======================================================================
ERROR: 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)
^^^^^^^^^^^^^^^^^^^
AttributeError: 'KidClass1' object has no attribute 'SECRET_PRESENT'

Stdout:
Дядо Коледа не е получил желания, отива да се депресира

======================================================================
ERROR: 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)
^^^^^^^^^^^^^^^^^^^
AttributeError: 'KidClass1' object has no attribute 'SECRET_PRESENT'

Stdout:
Дядо Коледа не е получил желания, отива да се депресира

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

Stdout:
KidClass1 received sirenie
KidClass1 received sirenie
KidClass2 received most wanted sirenie

======================================================================
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:
Дядо Коледа не е получил желания, отива да се депресира
Дядо Коледа не е получил желания, отива да се депресира
Дядо Коледа не е получил желания, отива да се депресира
Дядо Коледа не е получил желания, отива да се депресира
Дядо Коледа не е получил желания, отива да се депресира
KidClass1 received toy

----------------------------------------------------------------------
Ran 20 tests in 0.023s

FAILED (failures=2, errors=2)

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