Домашни > The Old Man from Scene #24 > Решения > Решението на Милан Георгиев

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

4 точки общо

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

  1import re
  2
  3class BridgeKeeper:
  4    def __init__(self, modul_name):
  5        self.modul = __import__(modul_name)
  6        self.objects = set()
  7
  8
  9    def __enter__(self):
 10        for line in dir(self.modul):
 11            curr = getattr(self.modul, line)
 12            name_check = self._what_is_your_name(curr)
 13            quest_check = self._what_is_your_quest(curr)
 14            random_check = self._what_is_theairspeedvelocityofunloadedswallow(curr)
 15
 16            if name_check and quest_check and random_check:
 17                self.objects.add(line)
 18        return self
 19
 20    def __getattr__(self, name):
 21        if name in self.objects:
 22            return getattr(self.modul, name)
 23        else:
 24            raise AttributeError(f"{name} fell into the oblivion at 11 meter/second case the swallow is European")
 25        
 26    def __exit__(self, exc_type, exc, tb):
 27        pass
 28
 29    def _what_is_your_name(self, target):
 30        name = getattr(target, '__name__', None)
 31        if isinstance(name, str) and name and name[0].isupper():
 32            return True
 33        return False    
 34
 35    def _create_dummy(self, target):
 36        obj = target.strip()
 37        if "|" in obj:
 38            obj = obj.split("|")[0]
 39            obj = obj.strip()
 40
 41        if obj == "int":
 42            return 0
 43        elif obj == "float":
 44            return 0.0
 45        elif obj == "str":
 46            return ""
 47        elif obj == "bool":
 48            return True
 49
 50        collections = re.match(r'(list|tuple|set)\[(.*)\]', obj)
 51        if collections:
 52            outer, inner = collections.groups()
 53            inner_dummy = self._create_dummy(inner)
 54            if outer == "list":
 55                return [inner_dummy]
 56            elif outer == "tuple":
 57                return (inner_dummy,)
 58            elif outer == "set":
 59                return {inner_dummy}
 60            
 61        is_dict = re.match(r'dict\[(.*),\s*(.*)\]', obj)
 62        if is_dict:
 63            key, value = is_dict.groups()
 64            return {self._create_dummy(key): self._create_dummy(value)}
 65        
 66        return None
 67
 68    def _what_is_your_quest(self, target):
 69        if not callable(target):
 70            return False
 71        docstring = getattr(target, "__doc__", "") or "" #добавих 'или' "", защото иначе ще е None
 72        dummy = []
 73
 74        pattern = r"Parameters\n----------\n(.*?)(?:\n\s*\n|$)"
 75        match = re.search(pattern, docstring, re.DOTALL)
 76
 77        if match:
 78            parameters = match.group(1).strip()
 79            for line in parameters.split('\n'):
 80                if ':' in line:
 81                    empty, actual = line.split(':', 1)
 82                    dummy.append(self._create_dummy(actual))
 83        try:
 84            target(*dummy)
 85            return True
 86        except:
 87            return False
 88        
 89    def _what_is_theairspeedvelocityofunloadedswallow(self, target):
 90        options = dir(target)
 91        for name in options:
 92            if name.startswith("__") and name.endswith("__"):
 93                continue
 94            if re.search(r'[aeiou]{4,}', name, re.IGNORECASE):
 95                continue
 96            chars = [char for char in name if char.isalpha()]
 97            if not chars:
 98                continue
 99            if not chars[-1].isupper():
100                continue
101            return True
102        return False

............F...........F
======================================================================
FAIL: test_rejects_callable_when_parameter_names_do_not_match (test.TestBridgeKeeper.test_rejects_callable_when_parameter_names_do_not_match)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/test.py", line 59, in test_rejects_callable_when_parameter_names_do_not_match
with self.assertRaises(AttributeError):
~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^
AssertionError: AttributeError not raised

======================================================================
FAIL: test_rejects_union_when_callable_does_not_support_all_union_branches (test.TestBridgeKeeper.test_rejects_union_when_callable_does_not_support_all_union_branches)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/test.py", line 72, in test_rejects_union_when_callable_does_not_support_all_union_branches
with self.assertRaises(AttributeError):
~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^
AssertionError: AttributeError not raised

----------------------------------------------------------------------
Ran 25 tests in 0.021s

FAILED (failures=2)

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