Дислектичен контекстен мениджър

Краен срок
23.11.2022 21:00

Срокът за предаване на решения е отминал

Дислексията е "затруднение с лексиката, предимно при четене и писане". Освен това определение, явно дислексията е толкова непонятна дори и на учените, че всяко друго описание би било или подвеждащо или outright offensive за хората с дислексия. И не че се опитваме да сме политически коректни, но така или иначе точната дефиниция на явлението е без значение за нашето предизвикателство. That being said:

Context manager, който помага при дислексия:

Искаме да направим контекстния мениджър Dyslexic, който да ни позволява да намираме атрибути на даден обект, дори да търсим с разместени букви (едно от проявленията на дислексията).
В случай, че дори и с разместване на буквите не може да бъде намерен такъв атрибут, искаме да възбудим грешка AttributeError със следния текст:
<The name of the class> object has no dyslexic attributes <the attribute searched for> (като очевидно двете неща в <> са плейсхолдъри).

class Baba:
    abc = 5

baba = Baba()

with Dyslexic(baba) as dyslexic_baba:
    print(dyslexic_baba.abc) # 5
    print(dyslexic_baba.bac) # 5
    print(dyslexic_baba.cab) # 5
    print(dyslexic_baba.notreal) # AttributeError: Baba object has no dyslexic attributes notreal

Бележки:

  • Ако имаме "колизия" в имената, т.е. baba има както атрибут abc, така и bca, а ние търсим baba.cab - няма значение кое ще се върне първо
  • За целта на предизвикателството не имплементираме поведение за set-ване на атрибути на обектите
  • След излизане от контекстният мениджър не искаме да имаме никаква промяна в поведението на оригиналния обект, в примера - baba

Решения

Виктор
  • Коректно
  • 5 успешни тест(а)
  • 0 неуспешни тест(а)
Виктор
import itertools
class Dyslexic:
def __init__(self, obj):
self._object = obj
def __enter__(self):
return self
def __exit__(self, exc_type, value, traceback):
pass
def __getattr__(self, name):
for permutation in itertools.permutations(name):
try:
return getattr(self._object, ''.join(permutation))
except AttributeError:
continue # Try another one
raise AttributeError(f'{self._object.__class__.__name__} object has no dyslexic attributes {name}')
.....
----------------------------------------------------------------------
Ran 5 tests in 0.077s

OK
Йордан Глигоров
  • Коректно
  • 5 успешни тест(а)
  • 0 неуспешни тест(а)
Йордан Глигоров
class Dyslexic():
def __init__(self, dyslexic_type):
self.dyslexic_type = dyslexic_type
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, exc_traceback):
if exc_type is not None and exc_value is not None and exc_traceback is not None:
raise
return self
def __getattr__(self, name):
dyslexic_type_variables = dir(self.dyslexic_type)
for variable in dyslexic_type_variables:
if (variable.startswith('__') and variable.endswith("__")) is False:
if sorted(name) == sorted(variable):
return getattr(self.dyslexic_type, variable)
raise AttributeError(f'{self.dyslexic_type.__class__.__name__} object has no dyslexic attributes {name}')
.....
----------------------------------------------------------------------
Ran 5 tests in 0.055s

OK
Александър Сариков
  • Коректно
  • 5 успешни тест(а)
  • 0 неуспешни тест(а)
Александър Сариков
import itertools
class Dyslexic:
def __init__(self, class_inst):
self.class_inst = class_inst
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
return
def __getattr__(self, attr):
for permutation in itertools.permutations(attr):
name_permutation = ''.join(permutation)
if hasattr(self.class_inst, name_permutation):
return getattr(self.class_inst, name_permutation)
raise AttributeError(f'{self.class_inst.__class__.__name__} object has no dyslexic attributes {attr}')
.....
----------------------------------------------------------------------
Ran 5 tests in 0.061s

OK
Емилиан Спасов
  • Некоректно
  • 2 успешни тест(а)
  • 3 неуспешни тест(а)
Емилиан Спасов
import itertools
import copy
class Helper:
def __init__(self, obj):
self._obj = copy.deepcopy(obj)
for attr in dir(obj):
if attr.startswith("__"):
continue
combs = [''.join(p) for p in itertools.permutations(attr)]
for comb in combs:
setattr(self._obj, comb, getattr(obj, attr))
def __getattr__(self, name):
if not hasattr(self._obj, name):
raise AttributeError(f"{self._obj.__class__.__name__} \
object has no dyslexic attributes {name}")
return getattr(self._obj, name)
class Dyslexic:
def __init__(self, obj):
self._helper = Helper(obj)
def __enter__(self):
return self._helper
def __exit__(self, exc_type, exc_value, exc_traceback):
pass
E.E.E
======================================================================
ERROR: test_attribute_not_found (test.TestDyslexicCM)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/storage/deedee/data/rails/pyfmi-2022/releases/20221115154139/lib/language/python/runner.py", line 67, in thread
    raise result
AttributeError: 'list' object attribute 'append' is read-only

======================================================================
ERROR: test_with_builtin (test.TestDyslexicCM)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/storage/deedee/data/rails/pyfmi-2022/releases/20221115154139/lib/language/python/runner.py", line 67, in thread
    raise result
AttributeError: 'range' object attribute 'count' is read-only

======================================================================
ERROR: test_with_function_call (test.TestDyslexicCM)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/storage/deedee/data/rails/pyfmi-2022/releases/20221115154139/lib/language/python/runner.py", line 67, in thread
    raise result
AttributeError: 'list' object attribute 'append' is read-only

----------------------------------------------------------------------
Ran 5 tests in 0.058s

FAILED (errors=3)
Сузана Петкова
  • Коректно
  • 5 успешни тест(а)
  • 0 неуспешни тест(а)
Сузана Петкова
import inspect
import itertools
class Dyslexic:
def __init__(self, object_):
self.object_ = object_
def __enter__(self):
obj = Dyslexic(self.object_)
return obj
def __getattr__(self, item):
new_keys = {}
attributes = []
for i in inspect.getmembers(self.object_):
if not i[0].startswith('_'):
if not inspect.ismethod(i[1]):
attributes.append(i)
for atrr in attributes:
key, val = atrr
for p in itertools.permutations(key):
new_keys[''.join(p)] = val
try:
return new_keys[item]
except KeyError:
raise AttributeError(item)
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is None:
return None
else:
print(f'{exc_type.__name__}: {type(self.object_).__name__} object has no dyslexic attributes {exc_val}')
return True
.....
----------------------------------------------------------------------
Ran 5 tests in 0.071s

OK
Кристиан Какалов
  • Некоректно
  • 4 успешни тест(а)
  • 1 неуспешни тест(а)
Кристиан Какалов
class AttributeError(Exception):
def __init__(self, message):
self._message = message
super().__init__(self._message)
class Dyslexic(object):
def __init__(self, obj):
self.__obj = obj
def __enter__(self):
return self
def __getattr__(self, attr):
for obj_attr in dir(self.__obj):
if sorted(obj_attr) == sorted(attr):
return getattr(self.__obj, obj_attr)
raise AttributeError(
f"{self.__obj.__class__.__name__} object has no dyslexic attributes {attr}")
def __exit__(self, type, value, traceback):
pass
E....
======================================================================
ERROR: test_attribute_not_found (test.TestDyslexicCM)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/storage/deedee/data/rails/pyfmi-2022/releases/20221115154139/lib/language/python/runner.py", line 67, in thread
    raise result
solution.AttributeError: list object has no dyslexic attributes no_such

----------------------------------------------------------------------
Ran 5 tests in 0.058s

FAILED (errors=1)
Виктор Христов
  • Некоректно
  • 4 успешни тест(а)
  • 1 неуспешни тест(а)
Виктор Христов
from itertools import permutations
class Dyslexic:
def __init__(self, obj):
self.obj = obj
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, exc_traceback):
pass
def __getattr__(self, name):
if (hasattr(self.obj, name)):
return getattr(self.obj, name)
else:
perms = [''.join(perm) for perm in permutations(name)]
for perm in perms:
if (hasattr(self.obj, perm)):
return getattr(self.obj, perm)
raise AttributeError(self.obj.__class__.__name__ + " has no dyslexic attributes " + name)
#bonus compacted solution
# |
# |
# \|/
"""
F,E=getattr,hasattr;from itertools import permutations as D
class A:
def __init__(A,obj):A.obj=obj
def __enter__(A):return A
def __exit__(A,exc_type,exc_value,exc_traceback):0
def __getattr__(A,name):
B=name
if E(A.obj,B):return F(A.obj,B)
else:
G=[''.join(A)for A in D(B)]
for C in G:
return F(A.obj,C) if E(A.obj,C) else 0
raise AttributeError(A.obj.__class__.__name__+' has no dyslexic attributes '+B)
"""
F....
======================================================================
FAIL: test_attribute_not_found (test.TestDyslexicCM)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/storage/deedee/data/rails/pyfmi-2022/releases/20221115154139/lib/language/python/runner.py", line 67, in thread
    raise result
AssertionError: 'list has no dyslexic attributes no_such' != 'list object has no dyslexic attributes no_such'
- list has no dyslexic attributes no_such
+ list object has no dyslexic attributes no_such
?      +++++++


----------------------------------------------------------------------
Ran 5 tests in 0.064s

FAILED (failures=1)
Йоанна Кръстева
  • Коректно
  • 5 успешни тест(а)
  • 0 неуспешни тест(а)
Йоанна Кръстева
import itertools
class Dyslexic(object):
def __init__(self, obj):
self.obj = obj
def __getattr__(self, attr):
flag = False
list_of_attributes = dir(self.obj)
del list_of_attributes[0:26]
permutations = list(itertools.permutations(attr))
for permutation in permutations:
att_name = ''.join(permutation)
if att_name in list_of_attributes:
flag = True
return getattr(self.obj, att_name)
if not flag:
error_message = f"{self.obj.__class__.__name__} object has no dyslexic attributes {attr}"
raise AttributeError(error_message)
def __enter__(self):
return self
def __exit__(self, _type, value, traceback):
pass
.....
----------------------------------------------------------------------
Ran 5 tests in 0.068s

OK
Роберт Борисов
  • Коректно
  • 5 успешни тест(а)
  • 0 неуспешни тест(а)
Роберт Борисов
def isequal(first_word, second_word):
if len(first_word) != len(second_word):
return False
for letter in first_word:
if first_word.count(letter) != second_word.count(letter):
return False
return True
class Dyslexic:
def __init__(self, obj):
self.obj = obj
def __enter__(self):
return Dyslexic(self.obj)
def __exit__(self, exc_type, exc_val, exc_tb):
pass
def __getattr__(self, item):
attributes = [attribute for attribute in dir(self.obj) if attribute[:2] != '__' and attribute[:-3:-1] != '__']
for attribute in attributes:
if isequal(attribute, item):
return getattr(self.obj, attribute)
raise AttributeError(f"{self.obj.__class__.__name__} object has no dyslexic attributes {item}")
.....
----------------------------------------------------------------------
Ran 5 tests in 0.055s

OK
Харут Партамиан
  • Некоректно
  • 1 успешни тест(а)
  • 4 неуспешни тест(а)
Харут Партамиан
from itertools import permutations
class Dyslexic:
def __init__(self, object_input):
self.copy_object = type(object_input)()
self.attributes = [(attribute, type(object_input).__dict__[attribute]) for attribute in
type(object_input).__dict__ if
not attribute.startswith("__") and not attribute.endswith("__")]
self.add_permutated_attributes_to_copy_object()
def generate_permutations(self):
permutated_attributes = []
converted_permutation = ""
for attribute in self.attributes:
for permutation in permutations(attribute[0]):
for char in permutation:
converted_permutation += char
permutated_attributes.append((converted_permutation, attribute[1]))
converted_permutation = ""
return permutated_attributes
def add_permutated_attributes_to_copy_object(self):
for pair in self.generate_permutations():
setattr(self.copy_object, pair[0], pair[1])
def __getattr__(self, item):
if hasattr(self.copy_object, item):
return getattr(self.copy_object, item)
raise AttributeError("{} object has no dyslexic attributes {}".format(self.copy_object.__class__.__name__, item))
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
pass
E.EEE
======================================================================
ERROR: test_attribute_not_found (test.TestDyslexicCM)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/storage/deedee/data/rails/pyfmi-2022/releases/20221115154139/lib/language/python/runner.py", line 67, in thread
    raise result
AttributeError: 'list' object attribute 'clear' is read-only

======================================================================
ERROR: test_with_builtin (test.TestDyslexicCM)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/storage/deedee/data/rails/pyfmi-2022/releases/20221115154139/lib/language/python/runner.py", line 67, in thread
    raise result
TypeError: range expected at least 1 argument, got 0

======================================================================
ERROR: test_with_custom_class (test.TestDyslexicCM)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/storage/deedee/data/rails/pyfmi-2022/releases/20221115154139/lib/language/python/runner.py", line 67, in thread
    raise result
AttributeError: Couple object has no dyslexic attributes opsish

======================================================================
ERROR: test_with_function_call (test.TestDyslexicCM)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/storage/deedee/data/rails/pyfmi-2022/releases/20221115154139/lib/language/python/runner.py", line 67, in thread
    raise result
AttributeError: 'list' object attribute 'clear' is read-only

----------------------------------------------------------------------
Ran 5 tests in 0.098s

FAILED (errors=4)
Радостин Маринов
  • Коректно
  • 5 успешни тест(а)
  • 0 неуспешни тест(а)
Радостин Маринов
from itertools import permutations
class Dyslexic:
def __init__(self, dyslexic_object):
self.dyslexic_object = dyslexic_object
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
return False
def __getattr__(self, item):
if hasattr(self.dyslexic_object, item):
return getattr(self.dyslexic_object, item)
else:
for permutation in (''.join(permutation_list) for permutation_list in permutations(item)):
if hasattr(self.dyslexic_object, permutation):
return getattr(self.dyslexic_object, permutation)
raise AttributeError(f"{type(self.dyslexic_object).__name__} object has no dyslexic attributes {item}")
.....
----------------------------------------------------------------------
Ran 5 tests in 0.061s

OK
Никола Михайлов
  • Коректно
  • 5 успешни тест(а)
  • 0 неуспешни тест(а)
Никола Михайлов
from itertools import permutations
class Dyslexic:
def __init__(self, obj):
self._obj = obj
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
if type is not None:
print(f"{type.__name__}: {value}")
return True
def __getattr__(self, name):
for permutation in permutations(name):
attribute = ''.join(permutation)
if(hasattr(self._obj, attribute)):
return getattr(self._obj, attribute)
raise AttributeError(f'{self._obj.__class__.__name__} object has no dyslexic attributes {name}')
.....
----------------------------------------------------------------------
Ran 5 tests in 0.060s

OK
Дейвид Каменов
  • Некоректно
  • 0 успешни тест(а)
  • 0 неуспешни тест(а)
Дейвид Каменов
class Dyslexic:
def __init__(self, attribute):
self.attribute = attribute
def __enter__(self):
return Baba()
def __exit__(self, type, value, traceback):
pass
class Baba:
abc = 5
def __getattr__(self, item):
if sorted(item) != sorted("abc"):
raise AttributeError(f"Baba object has no dyslexic attributes {item}")
else:
return self.abc
baba = Baba()
with Dyslexic(baba) as dyslexic_baba:
print(dyslexic_baba.abc) # 5
print(dyslexic_baba.bac) # 5
print(dyslexic_baba.cab) # 5
print(dyslexic_baba.notreal) # AttributeError: Baba object has no dyslexic attributes notreal
5
5
5
Baba object has no dyslexic attributes notreal
  File "/storage/deedee/data/rails/pyfmi-2022/releases/20221115154139/lib/language/python/runner.py", line 114, in main
    loaded_test = importlib.import_module('test', test_module)
  File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 883, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "/tmp/d20221123-4144380-1u4vn3/test.py", line 2, in <module>
    from solution import Dyslexic
  File "/tmp/d20221123-4144380-1u4vn3/solution.py", line 28, in <module>
    print(dyslexic_baba.notreal)  # AttributeError: Baba object has no dyslexic attributes notreal
  File "/tmp/d20221123-4144380-1u4vn3/solution.py", line 17, in __getattr__
    raise AttributeError(f"Baba object has no dyslexic attributes {item}")
Ивана Дончевска
  • Коректно
  • 5 успешни тест(а)
  • 0 неуспешни тест(а)
Ивана Дончевска
class Dyslexic:
def __init__(self, class_name):
self._class_name = class_name
def __enter__(self):
return self
def __exit__(self, exception_type, exception_value, exception_traceback):
if all(exception is not None for exception in [exception_type, exception_value, exception_traceback]):
raise
return self
def __getattr__(self, attribute):
attributes = dir(self._class_name)
for class_attribute in attributes:
if sorted(attribute) == sorted(class_attribute):
return getattr(self._class_name, class_attribute)
raise AttributeError(f'{type(self._class_name).__name__} object has no dyslexic attributes {attribute}')
.....
----------------------------------------------------------------------
Ran 5 tests in 0.053s

OK