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

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

3 точки общо

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

  1import re
  2
  3class Santa():
  4    gifts_list = []
  5    gifts_count = {}
  6    santas_dict = {}
  7    order = []
  8
  9    def common_gift(self):

Добре е това да е по-долу в списъка. След всички дъндъри. В момента имаш публичен метод, дъндъри, публичен метод, още дъндъри. По-подредено се чете по-лесно.

10 for gift in self.gifts_list: 11 self.gifts_count[gift] += 1 12 13 max = 0

Това е име на built-in функция. Не е добре да я замаскираш. А, ако имаш списък с всички подаръци, можеш да я използваш, за да вземеш най-искания - max(some_list, key=some_list.count)

14 present = '' 15 16 for gift in self.gifts_count: 17 if self.gifts_count[gift] > max: 18 max = self.gifts_count[gift] 19 present = gift 20 21 return present 22 23 def __new__(cls): 24 if not hasattr(cls, 'instance'): 25 cls.instance = super(Santa, cls).__new__(cls) 26 return cls.instance 27 28 def __call__(self, kid, zhelanie): 29 gift = re.search(r'[\'\"]+?([0-9a-zA-Z]+\s+)*[0-9a-zA-Z]+[\'\"]+?', zhelanie).group() 30 gift = re.sub('"', '', gift, count = 0)

С малко групи горе можеш да спестиш тези замествания.

31 gift = re.sub("'", '', gift, count = 0) 32 33 if id(kid) not in self.order: 34 self.order.append(id(kid)) 35 36 for idexes in Santa.santas_dict:

Бих казал, че indexes трябва да е key. Не циклиш по индекси, а по ключове. Също така трябва да е в единствено число, защото това държи един ключ, а не много.

37 if idexes is kid: 38 Santa.santas_dict[idexes] = gift 39 40 def __matmul__(self, pismo): 41 gift = re.search(r'[\'\"]+?([0-9a-zA-Z]+\s+)*[0-9a-zA-Z]+[\'\"]+?', pismo).group() 42 gift = re.sub('"', '', gift, count = 0) 43 gift = re.sub("'", '', gift, count = 0) 44 _id = re.search(r'[\n^]\s*\d+\s*[\n$]', pismo).group() 45 _id = re.sub(r'[(^\s+)(\s+$)]', '', _id) 46 47 if _id not in self.order:

Конвенцията за имена, които съвпадат с built-ins, е да слагаш долната черта в края - id_, а не в началото.

48 self.order.append(_id) 49 50 for idexes in Santa.santas_dict:

Ако това е речник, можеш просто да се опиташ да вземеш елемент с даден ключ. не е нужно да циклиш. Това е силата на речника.
Santa.santas_dict.get(some_key)

51 if str(id(idexes)) == _id: 52 Santa.santas_dict[idexes] = gift 53 54 def xmas(self): 55 common = self.common_gift() 56 57 for indexes in self.order: 58 for kids in self.santas_dict:

Отвново - това е едно дете, а не много деца. По-логично е да е for kid in...

59 if str(id(kids)) == str(indexes): 60 if kids.age < 6:

Тази шестица е добре да е константа.

61 kids.age += 1 62 if not kids.bad_kid and self.santas_dict[kids]: 63 kids.__call__(kids, self.santas_dict[kids])

Няма нужда да извикваш дъндъра. Можеш направо kids(self.santas_dict[kids])

64 65 elif kids.bad_kid: 66 kids.__call__('coal')

Неконсистента индентация.

67 68 else: 69 kids.__call__(common) 70 71 self.gifts_list.clear() 72 self.santas_dict.clear() 73 self.gifts_count.clear() 74 75 def __iter__(self):

Тъй като просто обхождаш списък, можеш просто return iter(self.gifts_list). Съответно няма да имаш нужда от __next__.

76 self.cur = 0 77 self.end = len(self.gifts_list) 78 return self 79 80 def __next__(self): 81 if self.cur < self.end: 82 res = self.gifts_list[self.cur] 83 self.cur += 1 84 return res 85 else: 86 raise StopIteration 87

Оставяй по два празни реда между дефиниции на top level.

88class Kid(type): 89 def __new__(cls, name, bases, attr_dict ):

Излишен интервал.

90 91 if '__call__' not in attr_dict: 92 raise NotImplementedError(f'много ви обичамe (или не :P)') 93 94 attr_dict['age'] = 0 95 attr_dict['bad_kid'] = False 96 97 def n(self):

Бих използвал по-описателно име.

98 Santa.santas_dict[self] = '' 99 100 for attributes in attr_dict: 101 if callable(attributes): 102 try: 103 return attributes(self) 104 except: 105 attr_dict['bad_kid'] = True

Помисли дали това ти върши работа. Променяш елемент от речник много след като той вече не се използва.

106 107 return self 108 109 attr_dict['__new__'] = n 110 instance = super().__new__(cls, name, bases, attr_dict ) 111 112 return instance

..FEFEEEF.E.EEEE.EEF
======================================================================
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 70, in test_call_and_mail_same_kid
self.santa @ f"'toy1'\n{id(kid1)}"
~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~
File "/tmp/solution.py", line 44, in __matmul__
_id = re.search(r'[\n^]\s*\d+\s*[\n$]', pismo).group()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'group'

======================================================================
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)}"
~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~
File "/tmp/solution.py", line 44, in __matmul__
_id = re.search(r'[\n^]\s*\d+\s*[\n$]', pismo).group()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'group'

======================================================================
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 87, in test_present_matching
self.santa @ f"""
File "/tmp/solution.py", line 41, in __matmul__
gift = re.search(r'[\'\"]+?([0-9a-zA-Z]+\s+)*[0-9a-zA-Z]+[\'\"]+?', pismo).group()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'group'

======================================================================
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 256, in test_santa_gift_order
self.santa @ f"'toy3'\n{id(kid3)}"
~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~
File "/tmp/solution.py", line 44, in __matmul__
_id = re.search(r'[\n^]\s*\d+\s*[\n$]', pismo).group()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'group'

======================================================================
ERROR: test_xmass (test.TestSanta.test_xmass)
Test a simple Christmas case.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/test.py", line 139, in test_xmass
self.santa @ f"'toy3'\n{id(kid3)}"
~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~
File "/tmp/solution.py", line 44, in __matmul__
_id = re.search(r'[\n^]\s*\d+\s*[\n$]', pismo).group()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'group'

======================================================================
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 173, in test_xmass_kid_without_a_wish
self.santa @ f"'toy2'\n{id(kid3)}"
~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~
File "/tmp/solution.py", line 44, in __matmul__
_id = re.search(r'[\n^]\s*\d+\s*[\n$]', pismo).group()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'group'

======================================================================
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 223, in test_xmass_naughty
kid1.public_with_error()
TypeError: TestSanta.<lambda>() missing 1 required positional argument: 'self'

======================================================================
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: type object 'KidClass1' has no attribute 'SECRET_PRESENT'

======================================================================
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: type object 'KidClass1' has no attribute 'SECRET_PRESENT'

======================================================================
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 246, in test_xmass_public_with_no_error
self.assertEqual(kid1.public_without_error(), 42)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: TestSanta.<lambda>() missing 1 required positional argument: 'self'

======================================================================
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 213, in test_xmass_years_5_and_over
self.assertEqual(kid1.SECRET_PRESENT, None)
^^^^^^^^^^^^^^^^^^^
AttributeError: type object 'KidClass1' has no attribute 'SECRET_PRESENT'

======================================================================
FAIL: test_call (test.TestSanta.test_call)
Test sending message via calling.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/test.py", line 56, in test_call
self.assertEqual(list(self.santa), ['toy1', 'toy2'])
AssertionError: Lists differ: [] != ['toy1', 'toy2']

Second list contains 2 additional elements.
First extra element 0:
'toy1'

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

======================================================================
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 else']

Second list contains 2 additional elements.
First extra element 0:
'something'

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

======================================================================
FAIL: 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 118, in test_signature_matching
self.assertEqual(kid1.SECRET_PRESENT, 'toy1')
AssertionError: 'toy3' != 'toy1'
- toy3
? ^
+ toy1
? ^

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

----------------------------------------------------------------------
Ran 20 tests in 0.024s

FAILED (failures=4, errors=11)

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