Предизвикателства > Разбий ни ключалката > Решения > Решението на Даниел Манчевски

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

0 точки общо

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

  1import types
  2import io
  3from functools import partial
  4from collections.abc import Iterator, Generator
  5
  6TYPE_DEFAULTS = {
  7    int: 0,
  8    float: 0.0,
  9    complex: 0j,
 10    bool: False,
 11    str: "a",
 12    list: [],
 13    tuple: (),
 14    range: range(0),
 15    bytes: b"",
 16    bytearray: bytearray(),
 17    memoryview: memoryview(b""),
 18    set: set(),
 19    frozenset: frozenset(),
 20    dict: {},
 21    type(None): None,
 22    type(Ellipsis): Ellipsis,
 23    type(NotImplemented): NotImplemented,
 24    types.FunctionType: lambda: None,
 25    types.LambdaType: lambda: None,
 26    types.MethodType: lambda: None,
 27    types.BuiltinFunctionType: lambda: None,
 28    types.BuiltinMethodType: lambda: None,
 29    partial: partial(lambda: None),
 30    Iterator: iter([]),
 31    Generator: (x for x in []),
 32    types.GeneratorType: (x for x in []),
 33    io.TextIOWrapper: io.StringIO(),
 34    io.BytesIO: io.BytesIO(),
 35    io.BufferedReader: io.BufferedReader(io.BytesIO()),
 36    staticmethod: staticmethod(lambda: None),
 37    classmethod: classmethod(lambda cls: None),
 38    property: property(lambda self: None),
 39    BaseException: BaseException(),
 40    Exception: Exception(),
 41    StopIteration: StopIteration(),
 42    types.ModuleType: types.ModuleType("dummy"),
 43    types.CodeType: (lambda: None).__code__,
 44    types.FrameType: None,
 45    types.TracebackType: None,
 46    type: type,
 47    object: object(),
 48    slice: slice(0),
 49    super: super,
 50    types.MethodWrapperType: object().__str__,
 51}
 52
 53
 54class LockPicker_2MI0600094:
 55    def __init__(self, lock):
 56        self.lock = lock
 57
 58    def unlock(self):
 59        args = []
 60
 61        while True:
 62            try:
 63                res = self.lock.pick(args)
 64                return res
 65            except Exception as ex:
 66                if isinstance(ex, TypeError):
 67                    if ex.position:
 68                        args[ex.position - 1] = TYPE_DEFAULTS.get(ex.expected, None)
 69                    else:
 70                        args += [9] * ex.expected
 71                if isinstance(ex, ValueError):
 72                    args[ex.position - 1] = ex.expected
 73
 74# class MyTypeError(TypeError):
 75#     def __init__(self, position, expected):
 76#         self.position = position
 77#         self.expected = expected
 78
 79
 80# class MyValueError(ValueError):
 81#     def __init__(self, position, expected):
 82#         self.position = position
 83#         self.expected = expected
 84
 85
 86# class Lock:
 87#     def __init__(self, *args):
 88#         self.ideal = list(*args)
 89
 90#     def pick(self, *args):
 91#         if len(self.ideal) != len(*args):
 92#             raise MyTypeError(None, len(self.ideal))
 93#         for i, el in enumerate(*args):
 94#             if type(el) is not type(self.ideal[i]):
 95#                 raise MyTypeError(i + 1, type(self.ideal[i]))
 96#             if el != self.ideal[i]:
 97#                 raise MyValueError(i + 1, self.ideal[i])
 98#         return True
 99
100
101# lock = Lock(["123", 65])
102# lock_picker = LockPicker_2MI0600094(lock)
103# print(lock_picker.unlock())

Грешка при опит за отключване:
Traceback (most recent call last):
File "/tmp/test.py", line 98, in <module>
test_unlocker(LockPicker(lock))
File "/usr/local/lib/python3.12/dist-packages/timeout_decorator/timeout_decorator.py", line 82, in new_function
return function(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^
File "/tmp/test.py", line 77, in test_unlocker
unlocker.unlock()
File "/tmp/solution.py", line 61, in unlock
while True:
^^^^
File "/usr/local/lib/python3.12/dist-packages/timeout_decorator/timeout_decorator.py", line 69, in handler
_raise_exception(timeout_exception, exception_message)
File "/usr/local/lib/python3.12/dist-packages/timeout_decorator/timeout_decorator.py", line 45, in _raise_exception
raise exception()
timeout_decorator.timeout_decorator.TimeoutError: 'Timed Out'

F
======================================================================
FAIL: test_picking (test.TestLockPicker.test_picking)
Ensure the lock is picked based on already stored boolean var.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/test.py", line 72, in test_picking
self.assertTrue(correct, "Не успя да отключиш.")
AssertionError: False is not true : Не успя да отключиш.

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (failures=1)

Дискусия
История

f1import typesf1import types
2import io2import io
3from functools import partial3from functools import partial
4from collections.abc import Iterator, Generator4from collections.abc import Iterator, Generator
55
6TYPE_DEFAULTS = {6TYPE_DEFAULTS = {
7    int: 0,7    int: 0,
8    float: 0.0,8    float: 0.0,
9    complex: 0j,9    complex: 0j,
10    bool: False,10    bool: False,
11    str: "a",11    str: "a",
12    list: [],12    list: [],
13    tuple: (),13    tuple: (),
14    range: range(0),14    range: range(0),
15    bytes: b"",15    bytes: b"",
16    bytearray: bytearray(),16    bytearray: bytearray(),
17    memoryview: memoryview(b""),17    memoryview: memoryview(b""),
18    set: set(),18    set: set(),
19    frozenset: frozenset(),19    frozenset: frozenset(),
20    dict: {},20    dict: {},
21    type(None): None,21    type(None): None,
22    type(Ellipsis): Ellipsis,22    type(Ellipsis): Ellipsis,
23    type(NotImplemented): NotImplemented,23    type(NotImplemented): NotImplemented,
24    types.FunctionType: lambda: None,24    types.FunctionType: lambda: None,
25    types.LambdaType: lambda: None,25    types.LambdaType: lambda: None,
26    types.MethodType: lambda: None,26    types.MethodType: lambda: None,
27    types.BuiltinFunctionType: lambda: None,27    types.BuiltinFunctionType: lambda: None,
28    types.BuiltinMethodType: lambda: None,28    types.BuiltinMethodType: lambda: None,
29    partial: partial(lambda: None),29    partial: partial(lambda: None),
30    Iterator: iter([]),30    Iterator: iter([]),
31    Generator: (x for x in []),31    Generator: (x for x in []),
32    types.GeneratorType: (x for x in []),32    types.GeneratorType: (x for x in []),
33    io.TextIOWrapper: io.StringIO(),33    io.TextIOWrapper: io.StringIO(),
34    io.BytesIO: io.BytesIO(),34    io.BytesIO: io.BytesIO(),
35    io.BufferedReader: io.BufferedReader(io.BytesIO()),35    io.BufferedReader: io.BufferedReader(io.BytesIO()),
36    staticmethod: staticmethod(lambda: None),36    staticmethod: staticmethod(lambda: None),
37    classmethod: classmethod(lambda cls: None),37    classmethod: classmethod(lambda cls: None),
38    property: property(lambda self: None),38    property: property(lambda self: None),
39    BaseException: BaseException(),39    BaseException: BaseException(),
40    Exception: Exception(),40    Exception: Exception(),
41    StopIteration: StopIteration(),41    StopIteration: StopIteration(),
n42    types.ModuleType: types.ModuleType('dummy'),n42    types.ModuleType: types.ModuleType("dummy"),
43    types.CodeType: (lambda: None).__code__,43    types.CodeType: (lambda: None).__code__,
n44    types.FrameType: None, n44    types.FrameType: None,
45    types.TracebackType: None,45    types.TracebackType: None,
46    type: type,46    type: type,
47    object: object(),47    object: object(),
48    slice: slice(0),48    slice: slice(0),
49    super: super,49    super: super,
n50    types.MethodWrapperType: object().__str__n50    types.MethodWrapperType: object().__str__,
51}51}
5252
nn53 
53class LockPicker_2MI0600094:54class LockPicker_2MI0600094:
n54 n
55    def __init__(self, lock):55    def __init__(self, lock):
56        self.lock = lock56        self.lock = lock
5757
58    def unlock(self):58    def unlock(self):
n59        self.args = []n59        args = []
60 
60        while(True):61        while True:
61            try:62            try:
n62                res=self.lock.pick(self.args)n63                res = self.lock.pick(args)
63                return res64                return res
64            except Exception as ex:65            except Exception as ex:
65                if isinstance(ex, TypeError):66                if isinstance(ex, TypeError):
n66                    if ex.position is None:n67                    if ex.position:
67                        self.args += [9] * ex.expected68                        args[ex.position - 1] = TYPE_DEFAULTS.get(ex.expected, None)
68                    else:69                    else:
nn70                        args += [9] * ex.expected
71                if isinstance(ex, ValueError):
69                        self.args[ex.position - 1] = TYPE_DEFAULTS.get(ex.expected, None)72                    args[ex.position - 1] = ex.expected
7073
n71                if isinstance(ex, ValueError):n74# class MyTypeError(TypeError):
72                    self.args[ex.position - 1] = ex.expected75#     def __init__(self, position, expected):
76#         self.position = position
77#         self.expected = expected
7378
tt79 
80# class MyValueError(ValueError):
81#     def __init__(self, position, expected):
82#         self.position = position
83#         self.expected = expected
84 
85 
86# class Lock:
87#     def __init__(self, *args):
88#         self.ideal = list(*args)
89 
90#     def pick(self, *args):
91#         if len(self.ideal) != len(*args):
92#             raise MyTypeError(None, len(self.ideal))
93#         for i, el in enumerate(*args):
94#             if type(el) is not type(self.ideal[i]):
95#                 raise MyTypeError(i + 1, type(self.ideal[i]))
96#             if el != self.ideal[i]:
97#                 raise MyValueError(i + 1, self.ideal[i])
98#         return True
99 
100 
101# lock = Lock(["123", 65])
102# lock_picker = LockPicker_2MI0600094(lock)
103# print(lock_picker.unlock())
104 
105 
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op