Предизвикателства > Сляпа баба > Решения > Решението на Георги Кунчев

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

3 точки общо

1 успешни теста
0 неуспешни теста
Код (Optimize)

 1import secret
 2
 3
 4FN = 'FN0123456789MI'
 5
 6
 7def is_interesting(obj, key, attr):
 8    """Check if a function is interesting and not a decoy."""
 9    if len(key) != 1:
10        return False
11    if not callable(attr):
12        return False
13    if getattr(type(obj), key, None) is attr:
14        return True
15    try:
16        attr()
17    except BaseException as exe:
18        if type(exe) is BaseException:
19            return True
20        if type(exe) is TypeError:
21            if str(exe) == 'Опаааааа, тука има нещо нередно.':
22                return True
23        try:
24            return attr(2) == 4 and attr(1) == 0
25        except:
26            pass
27    try:
28        return attr(left='6', right='9') == '69'
29    except:
30        return False
31
32
33def find_methods(obj):
34    """Collect all interesting methods."""
35    for key in dir(obj):
36        attr = getattr(obj, key)
37        if is_interesting(obj, key, attr):
38            yield key, attr
39        if 'clue' in key:
40            if found:=find_methods(attr):
41                yield from found
42
43
44def methodify():
45    """Construct a tuple, matching my FN, using interesting methods."""
46    methods = dict(find_methods(secret))
47    return tuple([methods[char] for char in FN])

Резултат от контролното:
30/30 верни отговора.
30 точки.
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

Дискусия
Георги Кунчев
20.11.2023 18:31

`if getattr(type(obj), key, None) is attr` гарантира статичен метод в класа. Хем методът е дефиниран в класа, хем идентитетът на метода, взет от класа, е същият като този от инстанцията, което, доколкото ми е понятно, е възможно само за статични методи. Относно грешката, това е заради вторият елемент от речника със сурови резултати. Добавих плейсхолдър, за да не се виждат публично истинските резултати. Махни го и ще е ок.
Мирослав Стояновски
20.11.2023 16:40

Когато пусна този код върху вашият secret.py файл, ми излиза някакъв KeyError. Защо се получава така ? Ето и снимка: https://ibb.co/R7h5xz9
Мирослав Стояновски
20.11.2023 16:28

Къде проверяваме дали функцията е staticmethod ?
История

f1import secretf1import secret
22
33
4FN = 'FN0123456789MI'4FN = 'FN0123456789MI'
55
66
7def is_interesting(obj, key, attr):7def is_interesting(obj, key, attr):
8    """Check if a function is interesting and not a decoy."""8    """Check if a function is interesting and not a decoy."""
n9    if (hasattr(type(obj), key)n9    if len(key) != 1:
10        return False
11    if not callable(attr):
12        return False
10        and getattr(type(obj), key) is attr13    if getattr(type(obj), key, None) is attr:
11        and callable(attr)):
12        return True14        return True
13    try:15    try:
14        attr()16        attr()
15    except BaseException as exe:17    except BaseException as exe:
16        if type(exe) is BaseException:18        if type(exe) is BaseException:
17            return True19            return True
18        if type(exe) is TypeError:20        if type(exe) is TypeError:
19            if str(exe) == 'Опаааааа, тука има нещо нередно.':21            if str(exe) == 'Опаааааа, тука има нещо нередно.':
20                return True22                return True
21        try:23        try:
n22            return attr(2) == 4 and attr(3) == 0n24            return attr(2) == 4 and attr(1) == 0
23        except Exception as exe:25        except:
24            return False26            pass
25    try:27    try:
n26        return attr(left='|_(.)', right='(.)_|') == '|_(.)(.)_|'n28        return attr(left='6', right='9') == '69'
27    except:29    except:
28        return False30        return False
2931
3032
31def find_methods(obj):33def find_methods(obj):
32    """Collect all interesting methods."""34    """Collect all interesting methods."""
33    for key in dir(obj):35    for key in dir(obj):
34        attr = getattr(obj, key)36        attr = getattr(obj, key)
n35        if len(key) == 1 and key in FN:n
36            if is_interesting(obj, key, attr):37        if is_interesting(obj, key, attr):
37                yield key, attr38            yield key, attr
38        if 'clue' in key:39        if 'clue' in key:
39            if found:=find_methods(attr):40            if found:=find_methods(attr):
40                yield from found41                yield from found
4142
4243
43def methodify():44def methodify():
44    """Construct a tuple, matching my FN, using interesting methods."""45    """Construct a tuple, matching my FN, using interesting methods."""
45    methods = dict(find_methods(secret))46    methods = dict(find_methods(secret))
t46    return tuple([methods[x] for x in FN])t47    return tuple([methods[char] for char in FN])
47 
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op

f1import secretf1import secret
22
33
4FN = 'FN0123456789MI'4FN = 'FN0123456789MI'
55
66
7def is_interesting(obj, key, attr):7def is_interesting(obj, key, attr):
8    """Check if a function is interesting and not a decoy."""8    """Check if a function is interesting and not a decoy."""
9    if (hasattr(type(obj), key)9    if (hasattr(type(obj), key)
10        and getattr(type(obj), key) is attr10        and getattr(type(obj), key) is attr
11        and callable(attr)):11        and callable(attr)):
12        return True12        return True
13    try:13    try:
14        attr()14        attr()
15    except BaseException as exe:15    except BaseException as exe:
16        if type(exe) is BaseException:16        if type(exe) is BaseException:
17            return True17            return True
18        if type(exe) is TypeError:18        if type(exe) is TypeError:
19            if str(exe) == 'Опаааааа, тука има нещо нередно.':19            if str(exe) == 'Опаааааа, тука има нещо нередно.':
20                return True20                return True
21        try:21        try:
22            return attr(2) == 4 and attr(3) == 022            return attr(2) == 4 and attr(3) == 0
23        except Exception as exe:23        except Exception as exe:
24            return False24            return False
25    try:25    try:
26        return attr(left='|_(.)', right='(.)_|') == '|_(.)(.)_|'26        return attr(left='|_(.)', right='(.)_|') == '|_(.)(.)_|'
27    except:27    except:
28        return False28        return False
2929
3030
31def find_methods(obj):31def find_methods(obj):
32    """Collect all interesting methods."""32    """Collect all interesting methods."""
33    for key in dir(obj):33    for key in dir(obj):
34        attr = getattr(obj, key)34        attr = getattr(obj, key)
t35        if key in FN:t35        if len(key) == 1 and key in FN:
36            if is_interesting(obj, key, attr):36            if is_interesting(obj, key, attr):
37                yield key, attr37                yield key, attr
38        if 'clue' in key:38        if 'clue' in key:
39            if found:=find_methods(attr):39            if found:=find_methods(attr):
40                yield from found40                yield from found
4141
4242
43def methodify():43def methodify():
44    """Construct a tuple, matching my FN, using interesting methods."""44    """Construct a tuple, matching my FN, using interesting methods."""
45    methods = dict(find_methods(secret))45    methods = dict(find_methods(secret))
46    return tuple([methods[x] for x in FN])46    return tuple([methods[x] for x in FN])
4747
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op