Тайнопис за начинаещи

Краен срок
19.11.2022 18:00

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

Криптографията, или както в българската Уикипедия страница пише - "Тайнопис", е много обширна наука, в която няма как да навлезем в рамките на едно предизвикателство.
Накратко - занимава се с това как се преобразува информация, така че тя да е нечетима / неразбираема (или поне за тези, без знанията да разшифрират резултата).

За целите на предизвикателството ще разгледаме няколко свръх-прости шифъра:

ROT-13

ROT-13 e прост субституционен шифър, при който всяка буква в азбуката (ние ще работим само с английската азбука от 26 букви) бива изместена с 13 позиции. Ето ви една описателна картинка, а ако искате да тествате как работи - rot13.com:

Atbash

Atbash е друг субституционен шифър, при който всяка буква в азбуката бива заместена с "огледалната" ѝ. С други думи A, първата буква, бива заместена със Z, последната буква. ABC става ZYX.

FN-XOR

FN-XOR няма... Или поне до този момент!
FN-XOR ще бъде вид XOR шифър, който се класифицира като адитивен шифър. Идеята на XOR шифрите е да използват ключ, с помощта на който да криптират даден текст, използвайки XOR операцията.

Как ще работи при нас

Ключ ще бъде вашият факултетен номер (повярвайте ми, искате да е конкретно вашият) в string формат.
ASCII кодът на всяка буква от съобщението за криптиране ще бъде XOR-нат с респективната буква (или цифра) от ключът ви. Ако съобщението е по-дълго от ключа ви (доста вероятно), "итерирането" по ключа просто започва отначало.
Резултатът от XOR операцията се интерпретира като ASCII код - взимаме символа, отговарящ на този код, и накрая получаваме криптиран низ.

Може би един пример ще е по-описателен:

Ключ - '61301'
Съобщение - 'Cryptography'

1. 'C' и '6' (първата буква на съобщението, първият символ на ключа) -> 67 ^ 54 (XOR) -> 117 (резултат от XOR - ASCII код) -> 'u' (символът, който отговаря на ASCII кода 117)
2. 'r' и '1' (втората буква на съобщението, вторият символ на ключа) -> 114 ^ 49 (XOR) -> 67 (резултат от XOR - ASCII код) -> 'C' (символът, който отговаря на ASCII кода 67)
3. ...
4. ...
5. ...
6. 'o' и '6' (шестата буква на съобщението, символите на ключа "свършиха", така че започваме от първия) -> 111 ^ 54 -> 89 -> 'Y'
И така нататък...

Накрая получаваме:
uCJ@EYVAQA^H

И след всичките тези шифри, какво?

Искаме да направим декоратор encrypt_message, който да прилагаме върху функции, които връщат стринг като резултат от изпълнението си. Искаме декораторът да приема един от следните 3 стринга:

  • 'ROT-13' - използва ROT-13 криптиране
  • 'ATBASH' - използва Atbash криптиране
  • 'FN-XOR' - използва нашето лично FN-XOR криптиране

Ето ви примери с код:

@encrypt_message('ROT-13')
def michael_bolton():
    return 'This is the tale of Captain Jack Sparrow!'

print(michael_bolton()) # Guvf vf gur gnyr bs Pncgnva Wnpx Fcneebj!
@encrypt_message('ATBASH')
def michael_bolton(person):
    return f'This is the tale of {person}!'

print(michael_bolton('Captain Jack Sparrow')) # Gsrh rh gsv gzov lu Xzkgzrm Qzxp Hkziild!
@encrypt_message('FN-XOR')
def michael_bolton(person, description):
    return f'This is the tale of {person}, {description}!'

print(michael_bolton('Captain Jack Sparrow', 'pirate so brave of the Seven Seas')) # bYZC_BDYSGQ]S\VuPCDP__zPUZcAWCA_FCYCWEVBYQBP@T_WE[UeTEU_bVQB

# В горното има шибани unicode символи, не го мислете, ние ще го мислим
# Също така, при вас ще е различно, защото ще използвате друг факултетен номер :p

Беше ми обещан бонус!

Сигурно се чудите къде ви е бонусът... Ако се справите успешно с предизвикателството, в output-а на тестовете ще намерите броят точки, които имате от контролното.
Ако искате да ги знаете преди да ги качим официално (с други думи с някой друг ден пред останалите) - успех с предизвикателството! :grin:

Бележки:

  • За ROT-13 и Atbash заместваме само буквите от английската азбука. Големите се заместват с големи, малките - с малки.
  • За FN-XOR всичко се прекарва през XOR алгоритъма - няма значение дали са букви или други символи
  • Няма да тестваме със символи извън ASCII таблицата (макар че не би следвало да има значение)
  • Няма да тестваме с функции с keyword аргументи

Решения

Виктор
  • Коректно
  • 7 успешни тест(а)
  • 0 неуспешни тест(а)
Виктор
import codecs
from itertools import cycle
from string import ascii_lowercase as lower
from string import ascii_uppercase as upper
FN = '61301'
def rot_13(text):
return codecs.encode(text, 'rot_13')
def atbash(text):
return text.translate(str.maketrans(lower + upper, lower[::-1] + upper[::-1]))
def fn_xor(text):
return ''.join(chr(ord(c) ^ ord(k)) for (c, k) in zip(text, cycle(FN)))
def encrypt_message(encryption):
def encrypt(function):
def encrypted(*args, **kwargs):
encryption_algorithms = {'ROT-13': rot_13, 'ATBASH': atbash, 'FN-XOR': fn_xor}
return encryption_algorithms[encryption](function(*args, **kwargs))
return encrypted
return encrypt
=======================================================================
   Честито! Ти успя да видиш резултатите си преди останалите плебеи:
      Брой верни отговори: 52.33лв
      Брой получени точки: голямата примоция
=======================================================================
.......
----------------------------------------------------------------------
Ran 7 tests in 0.079s

OK
Никола Михайлов
  • Коректно
  • 7 успешни тест(а)
  • 0 неуспешни тест(а)
Никола Михайлов
KEY = '62579'
def encrypt_message(encoding_method):
return lambda function: lambda *args: ''.join([chr(ord(char) + (13 if 'a' <= char < 'n' or char < 'N' else -13)) if char.isalpha() else char for char in function(*args)]) if encoding_method == 'ROT-13' else ''.join([chr(ord('a') + ord('z') - ord(char)) if char.islower() else chr(ord('A') + ord('Z') - ord(char)) if char.isalpha() else char for char in function(*args)]) if encoding_method == 'ATBASH' else ''.join([chr(ord(char) ^ ord(KEY[index % len(KEY)])) for index, char in enumerate(function(*args))])
=======================================================================
   Честито! Ти успя да видиш резултатите си преди останалите плебеи:
      Брой верни отговори: 22
      Брой получени точки: 25
=======================================================================
.......
----------------------------------------------------------------------
Ran 7 tests in 0.073s

OK
Цветелина Чакърова
  • Коректно
  • 7 успешни тест(а)
  • 0 неуспешни тест(а)
Цветелина Чакърова
def encrypt_message(encryption_type):
def encrypt_message_decorator(func):
def encyption_algorithm(*args):
string_to_encrypt = func(*args)
string_result = ''
if encryption_type == 'ROT-13':
for symbol in string_to_encrypt:
if 'a' <= symbol <= 'm' or 'A' <= symbol <= 'M':
string_result += chr(ord(symbol) + 13)
elif 'n' <= symbol <= 'z' or 'N' <= symbol <= 'Z':
string_result += chr(ord(symbol) - 13)
else:
string_result += symbol
elif encryption_type == 'ATBASH':
for symbol in string_to_encrypt:
if 'a' <= symbol <= 'z':
string_result += chr(ord('a') - ord(symbol) + ord('z'))
elif 'A' <= symbol <= 'Z':
string_result += chr(ord('A') - ord(symbol) + ord('Z'))
else:
string_result += symbol
elif encryption_type == 'FN-XOR':
FN = '62553'
FN_index = 0
for symbol in string_to_encrypt:
string_result += chr(ord(symbol) ^ ord(FN[FN_index]))
if FN_index == len(FN) - 1:
FN_index = 0
else:
FN_index += 1
return string_result
return encyption_algorithm
return encrypt_message_decorator
=======================================================================
   Честито! Ти успя да видиш резултатите си преди останалите плебеи:
      Брой верни отговори: 22
      Брой получени точки: 25
=======================================================================
.......
----------------------------------------------------------------------
Ran 7 tests in 0.071s

OK
Георги Събев
  • Коректно
  • 7 успешни тест(а)
  • 0 неуспешни тест(а)
Георги Събев
SMALL_LETTERS = "abcdefghijklmnopqrstuvwxyz"
CAPITAL_LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
SMALL_LETTERS_REVERSED = SMALL_LETTERS[::-1]
CAPITAL_LETTERS_REVERSED = CAPITAL_LETTERS[::-1]
FN = '62380'
def repeat_string(str, length):
times = (length // len(str)) + 1
return (str * times)[:length]
def rot13(str):
result = ""
for symbol in str:
if symbol in SMALL_LETTERS:
result += SMALL_LETTERS[(SMALL_LETTERS.find(symbol) + 13) % 26]
elif symbol in CAPITAL_LETTERS:
result += CAPITAL_LETTERS[(CAPITAL_LETTERS.find(symbol) + 13) % 26]
else:
result += symbol
return result
def atbash(str):
result = ""
for symbol in str:
if symbol in SMALL_LETTERS:
result += SMALL_LETTERS_REVERSED[SMALL_LETTERS.find(symbol)]
elif symbol in CAPITAL_LETTERS:
result += CAPITAL_LETTERS_REVERSED[CAPITAL_LETTERS.find(symbol)]
else:
result += symbol
return result
def fn_xor(str):
result = ""
extended_fn = repeat_string(FN, len(str))
for s1, s2 in zip(str, extended_fn):
result += chr(ord(s1) ^ ord(s2))
return result
def encrypt_message(algorithm):
def decorator(func):
def message(*args, **kwargs):
if algorithm == 'ROT-13':
return rot13(func(*args, **kwargs))
elif algorithm == 'ATBASH':
return atbash(func(*args, **kwargs))
elif algorithm == 'FN-XOR':
return fn_xor(func(*args, **kwargs))
return message
return decorator
=======================================================================
   Честито! Ти успя да видиш резултатите си преди останалите плебеи:
      Брой верни отговори: 20
      Брой получени точки: 23
=======================================================================
.......
----------------------------------------------------------------------
Ran 7 tests in 0.070s

OK
Йордан Глигоров
  • Некоректно
  • 4 успешни тест(а)
  • 3 неуспешни тест(а)
Йордан Глигоров
import string
def atbash(message):
lookup_table = {
'A': 'Z', 'B': 'Y', 'C': 'X', 'D': 'W', 'E': 'V',
'a': 'z', 'b': 'y', 'c': 'x', 'd': 'w', 'e': 'v',
'F': 'U', 'G': 'T', 'H': 'S', 'I': 'R', 'J': 'Q',
'f': 'u', 'g': 't', 'h': 's', 'i': 'r', 'j': 'q',
'K': 'P', 'L': 'O', 'M': 'N', 'N': 'M', 'O': 'L',
'k': 'p', 'l': 'o', 'm': 'n', 'n': 'm', 'o': 'l',
'P': 'K', 'Q': 'J', 'R': 'I', 'S': 'H', 'T': 'G',
'p': 'k', 'q': 'j', 'r': 'i', 's': 'h', 't': 'g',
'U': 'F', 'V': 'E', 'W': 'D', 'X': 'C', 'Y': 'B', 'Z': 'A',
'u': 'f', 'v': 'e', 'w': 'd', 'x': 'c', 'y': 'b', 'z': 'a',
' ': ' ', '!': '!', '.': '.', '?': '?'
}
valid_letters = list(lookup_table.keys())
return "".join([lookup_table[letter] for letter in message if letter in valid_letters])
def rot_13(message):
lower_letters = string.ascii_lowercase
upper_letters = string.ascii_uppercase
result = []
for letter in message:
if 'A' <= letter <= 'Z':
result.append(upper_letters[(upper_letters.index(letter) + 13 ) % 26])
elif 'a' <= letter <= 'z':
result.append(lower_letters[(lower_letters.index(letter) + 13) % 26])
else:
result.append(letter)
return "".join(result)
def fn_xor(message):
# fn ='61301'
i = 0
fn = '855366'
fn_len = len(fn)
result = []
for letter in message:
if i >= fn_len:
i = 0
result.append(chr(ord(letter) ^ ord(fn[i])))
i += 1
return "".join(result)
def encrypt_message(function_name):
def decorator(func):
def encrypt(*args):
if function_name == "ROT-13":
return rot_13(func(*args))
elif function_name == "ATBASH":
return atbash(func(*args))
elif function_name == "FN-XOR":
return fn_xor(func(*args))
return encrypt
return decorator
=======================================================================
   Честито! Ти успя да видиш резултатите си преди останалите плебеи:
      Брой верни отговори: 23
      Брой получени точки: 27
=======================================================================
.FFF...
======================================================================
FAIL: test_atbash_empty_args (test.TestEncryptMessage)
Test for all chars in ATBASH with a function with empty args
----------------------------------------------------------------------
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: 'zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA' != 'zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA0123456789'
- zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA
+ zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA0123456789
?                                                     ++++++++++


======================================================================
FAIL: test_atbash_is_inverse (test.TestEncryptMessage)
Test that the ATBASH encryption is it's own inverse
----------------------------------------------------------------------
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: 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' != 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
- abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
+ abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
?                                                     ++++++++++


======================================================================
FAIL: test_atbash_with_args (test.TestEncryptMessage)
Test for all chars in ATBASH with a function with non-empty args
----------------------------------------------------------------------
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: 'zyxwvutsrqponmlkjihgfedcba ZYXWVUTSRQPONMLKJIHGFEDCBA !' != 'zyxwvutsrqponmlkjihgfedcba, ZYXWVUTSRQPONMLKJIHGFEDCBA, 0123456789!'
- zyxwvutsrqponmlkjihgfedcba ZYXWVUTSRQPONMLKJIHGFEDCBA !
?                                                      ^
+ zyxwvutsrqponmlkjihgfedcba, ZYXWVUTSRQPONMLKJIHGFEDCBA, 0123456789!
?                           +                           ^^^^^^^^^^^^


----------------------------------------------------------------------
Ran 7 tests in 0.081s

FAILED (failures=3)
Радостин Маринов
  • Коректно
  • 7 успешни тест(а)
  • 0 неуспешни тест(а)
Радостин Маринов
from itertools import cycle
def plus_13(char):
if char < 'A' or 'Z' < char < 'a' or char > 'z':
return char
if char.islower():
return chr(((ord(char) - ord('a')) + 13) % 26 + ord('a'))
return chr(((ord(char) - ord('A')) + 13) % 26 + ord('A'))
def subtract_from_25(char):
if char < 'A' or 'Z' < char < 'a' or char > 'z':
return char
if char.islower():
return chr(ord('z') - ord(char) + ord('a'))
return chr(ord('Z') - ord(char) + ord('A'))
def rot_13(string):
return ''.join((plus_13(char) for char in string))
def atbash(string):
return ''.join((subtract_from_25(char) for char in string))
def fn_xor(string):
return ''.join((chr(ord(inputChar) ^ ord(keyChar)) for inputChar, keyChar in zip(string, cycle('62449'))))
def encrypt_message(enc_type):
def decorator(func):
def encrypted(*args, **kwargs):
if enc_type == 'ROT-13':
return rot_13(func(*args, **kwargs))
elif enc_type == 'ATBASH':
return atbash(func(*args, **kwargs))
elif enc_type == 'FN-XOR':
return fn_xor(func(*args, **kwargs))
else:
return func(*args, **kwargs)
return encrypted
return decorator
=======================================================================
   Честито! Ти успя да видиш резултатите си преди останалите плебеи:
      Брой верни отговори: 22
      Брой получени точки: 25
=======================================================================
.......
----------------------------------------------------------------------
Ran 7 tests in 0.073s

OK
Петър Тодоров
  • Коректно
  • 7 успешни тест(а)
  • 0 неуспешни тест(а)
Петър Тодоров
FN = "31621"
def encrypt_message(msg):
def decorator(func):
def cached_server(*args):
if msg == "FN-XOR":
return XOR_FN(func(*args))
elif msg == "ATBASH":
return Atbash(func(*args))
elif msg == "ROT-13":
return ROT_13(func(*args))
return cached_server
return decorator
def XOR_FN(str):
res = ""
n = len(str)
for i in range(n):
res += chr(ord(str[i]) ^ ord(FN[i % 5]))
return res
def ROT_13(str):
res = ""
for ch in str:
if not ch.isalpha():
res += ch
continue
number = ord(ch)
if 91 > number > 77 or number > 109:
res += chr(ord(ch) - 13)
else:
res += chr(ord(ch) + 13)
return res
def Atbash(str):
res = ""
for ch in str:
if not ch.isalpha():
res += ch
continue
num = ord(ch)
if num > 96:
res += chr(122 + 97 - num)
else:
res += chr(90 + 65 - num)
return res
=======================================================================
   Честито! Ти успя да видиш резултатите си преди останалите плебеи:
      Брой верни отговори: 16
      Брой получени точки: 18
=======================================================================
.......
----------------------------------------------------------------------
Ran 7 tests in 0.072s

OK
Мариян Христов
  • Коректно
  • 7 успешни тест(а)
  • 0 неуспешни тест(а)
Мариян Христов
def encrypt_message(type):
return lambda to_decorate : (lambda *args, **kwargs : {'ROT-13': ''.join(dict(zip(''.join([chr(letter) for letter in range(ord('a'), ord('z') + 1)][26::1] + [chr(letter) for letter in range(ord('a'), ord('z') + 1)][:26:1] + [chr(letter).upper() for letter in range(ord('a'), ord('z') + 1)][26::1] + [chr(letter).upper() for letter in range(ord('a'), ord('z') + 1)][:26:1]), ''.join([chr(letter) for letter in range(ord('a'), ord('z') + 1)][13::1] + [chr(letter) for letter in range(ord('a'), ord('z') + 1)][:13:1] + [chr(letter).upper() for letter in range(ord('a'), ord('z') + 1)][13::1] + [chr(letter).upper() for letter in range(ord('a'), ord('z') + 1)][:13:1]))).get(char, char) for char in to_decorate(*args,**kwargs)), 'ATBASH': ''.join(dict(zip(''.join([chr(letter) for letter in range(ord('a'), ord('z') + 1)][26::1] + [chr(letter) for letter in range(ord('a'), ord('z') + 1)][:26:1] + [chr(letter).upper() for letter in range(ord('a'), ord('z') + 1)][26::1] + [chr(letter).upper() for letter in range(ord('a'), ord('z') + 1)][:26:1]), ''.join([chr(letter) for letter in range(ord('a'), ord('z') + 1)][-1::-1] + [chr(letter) for letter in range(ord('a'), ord('z') + 1)][:-1:-1] + [chr(letter).upper() for letter in range(ord('a'), ord('z') + 1)][-1::-1] + [chr(letter).upper() for letter in range(ord('a'), ord('z') + 1)][:-1:-1]))).get(char, char) for char in to_decorate(*args,**kwargs)), 'FN-XOR': ''.join([chr(ord(char) ^ ord('7MI0600042'[i % len('7MI0600042')])) for i, char in enumerate(to_decorate(*args,**kwargs))])}[type])
=======================================================================
   Честито! Ти успя да видиш резултатите си преди останалите плебеи:
      Брой верни отговори: 15
      Брой получени точки: 17
=======================================================================
.......
----------------------------------------------------------------------
Ran 7 tests in 0.197s

OK
Емилиан Спасов
  • Коректно
  • 7 успешни тест(а)
  • 0 неуспешни тест(а)
Емилиан Спасов
from abc import ABC, abstractmethod
LETTER_TO_ROT13_CONVERSION = {
'a': 'n',
'b': 'o',
'c': 'p',
'd': 'q',
'e': 'r',
'f': 's',
'g': 't',
'h': 'u',
'i': 'v',
'j': 'w',
'k': 'x',
'l': 'y',
'm': 'z',
'n': 'a',
'o': 'b',
'p': 'c',
'q': 'd',
'r': 'e',
's': 'f',
't': 'g',
'u': 'h',
'v': 'i',
'w': 'j',
'x': 'k',
'y': 'l',
'z': 'm',
}
LETTER_TO_ATBASH_CONVERSION = {
'a': 'z',
'b': 'y',
'c': 'x',
'd': 'w',
'e': 'v',
'f': 'u',
'g': 't',
'h': 's',
'i': 'r',
'j': 'q',
'k': 'p',
'l': 'o',
'm': 'n',
'n': 'm',
'o': 'l',
'p': 'k',
'q': 'j',
'r': 'i',
's': 'h',
't': 'g',
'u': 'f',
'v': 'e',
'w': 'd',
'x': 'c',
'y': 'b',
'z': 'a',
}
class Encrypter(ABC):
@abstractmethod
def encrypt(self, message: str) -> str:
pass
class ROT13Encrypter(Encrypter):
def encrypt(self, message):
result = []
for char in message:
if char.lower() not in LETTER_TO_ROT13_CONVERSION:
result.append(char)
continue
if char.isupper():
new_char = LETTER_TO_ROT13_CONVERSION[char.lower()]
result.append(new_char.upper())
else:
result.append(LETTER_TO_ROT13_CONVERSION[char])
return ''.join(result)
class AtbashEncrypter(Encrypter):
def encrypt(self, message):
result = []
for char in message:
if char.lower() not in LETTER_TO_ATBASH_CONVERSION:
result.append(char)
continue
if char.isupper():
new_char = LETTER_TO_ATBASH_CONVERSION[char.lower()]
result.append(new_char.upper())
else:
result.append(LETTER_TO_ATBASH_CONVERSION[char])
return ''.join(result)
class FNXOREncrypter(Encrypter):
def __init__(self, key="62617"):
self._key = key
def encrypt(self, message):
result = []
for i, char in enumerate(message):
encryption_char = self._key[i % len(self._key)]
new_ascii_value = ord(char) ^ ord(encryption_char)
result.append(chr(new_ascii_value))
return ''.join(result)
class DefaultEncrypter(Encrypter):
def encrypt(self, message):
return message
def getEncrypter(cipher: str) -> Encrypter:
match cipher.upper():
case "ROT-13": return ROT13Encrypter()
case "ATBASH": return AtbashEncrypter()
case "FN-XOR": return FNXOREncrypter()
case _: return DefaultEncrypter()
def message_encrypter(message, cipher):
return getEncrypter(cipher).encrypt(message)
def encrypt_message(cipher: str):
def func_wrapper(get_message):
def argument_wrapper(*args, **kwargs):
message = get_message(*args, **kwargs)
if type(message) is not str:
return message
return getEncrypter(cipher).encrypt(message)
return argument_wrapper
return func_wrapper
=======================================================================
   Честито! Ти успя да видиш резултатите си преди останалите плебеи:
      Брой верни отговори: 18
      Брой получени точки: 21
=======================================================================
.......
----------------------------------------------------------------------
Ran 7 tests in 0.070s

OK
Роберт Борисов
  • Некоректно
  • 0 успешни тест(а)
  • 0 неуспешни тест(а)
Роберт Борисов
from itertools import cycle
def encrypt_message(encoding_type):
def encrypt_decorator(func):
def encrypted(*args):
if encoding_type == 'ROT-13':
result = ''
for symbol in func():
if symbol.islower():
result += chr((ord(symbol) - ord('a') + 13) % 26 + ord('a'))
elif symbol.isupper():
result += chr((ord(symbol) - ord('A') + 13) % 26 + ord('A'))
else:
result += symbol
return result
elif encoding_type == 'ATBASH':
result = ''
first_half = [chr(a) for a in range(97, 110)]
second_half = [chr(a) for a in range(122, 109, -1)]
for symbol in func(*args):
if 'n' <= symbol.lower() <= 'z':
symbol_index = second_half.index(symbol.lower())
if symbol.islower():
result += first_half[symbol_index]
else:
result += first_half[symbol_index].upper()
elif 'a' <= symbol.lower() <= 'm':
symbol_index = first_half.index(symbol.lower())
if symbol.islower():
result += second_half[symbol_index]
else:
result += second_half[symbol_index].upper()
else:
result += symbol
return result
elif encoding_type == 'FN-XOR':
result = ''
fn = cycle([6, 2, 5, 2, 9])
for symbol in func(*args):
result += chr(ord(symbol) ^ next(fn))
return result
return encrypted
return encrypt_decorator
Invalid result for FN-XOR.
  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/d20221119-4144380-r7t3l4/test.py", line 169, in <module>
    raise Exception('Invalid result for FN-XOR.')
Ивана Дончевска
  • Коректно
  • 7 успешни тест(а)
  • 0 неуспешни тест(а)
Ивана Дончевска
from itertools import cycle
from codecs import encode
lower_cases_alphabet = {'a': 'z', 'b': 'y', 'c': 'x', 'd': 'w', 'e': 'v',
'f': 'u', 'g': 't', 'h': 's', 'i': 'r', 'j': 'q',
'k': 'p', 'l': 'o', 'm': 'n', 'n': 'm', 'o': 'l',
'p': 'k', 'q': 'j', 'r': 'i', 's': 'h', 't': 'g',
'u': 'f', 'v': 'e', 'w': 'd', 'x': 'c', 'y': 'b', 'z': 'a'}
upper_cases_alphabet = {'A': 'Z', 'B': 'Y', 'C': 'X', 'D': 'W', 'E': 'V',
'F': 'U', 'G': 'T', 'H': 'S', 'I': 'R', 'J': 'Q',
'K': 'P', 'L': 'O', 'M': 'N', 'N': 'M', 'O': 'L',
'P': 'K', 'Q': 'J', 'R': 'I', 'S': 'H', 'T': 'G',
'U': 'F', 'V': 'E', 'W': 'D', 'X': 'C', 'Y': 'B', 'Z': 'A'}
def rot_13(message):
return encode(message, 'rot_13')
def atbash(message):
encrypted_message = ""
for letter in message:
if letter in upper_cases_alphabet:
encrypted_message += upper_cases_alphabet[letter]
elif letter in lower_cases_alphabet:
encrypted_message += lower_cases_alphabet[letter]
else:
encrypted_message += letter
return encrypted_message
def fn_xor(message):
key = "855364"
encrypted_string = ""
for number, letter in zip(cycle(key), message):
encrypted_string += (chr(ord(number) ^ ord(letter)))
return encrypted_string
def encrypt_message(name_of_function):
def decorator(function):
def encrypt_data(*args):
if name_of_function == "ROT-13":
return rot_13(function(*args))
elif name_of_function == "ATBASH":
return atbash(function(*args))
elif name_of_function == "FN-XOR":
return fn_xor(function(*args))
return encrypt_data
return decorator
=======================================================================
   Честито! Ти успя да видиш резултатите си преди останалите плебеи:
      Брой верни отговори: 16
      Брой получени точки: 18
=======================================================================
.......
----------------------------------------------------------------------
Ran 7 tests in 0.083s

OK
Йоан Бабулков
  • Коректно
  • 7 успешни тест(а)
  • 0 неуспешни тест(а)
Йоан Бабулков
from enum import Enum
from itertools import cycle
lower_alph = "abcdefghijklmnopqrstuvwxyz"
upper_alph = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
class Crypts(str, Enum):
rot13 = "ROT-13",
atbash = "ATBASH",
fnxor = "FN-XOR"
def ROT13(message):
return "".join(map(lambda x: lower_alph[(lower_alph.index(x) + 13) % 26] if x.islower() else upper_alph[
(upper_alph.index(x) + 13) % 26] if x.isupper() else x, message))
def atbash(message):
return "".join(map(lambda x: lower_alph[25 - lower_alph.index(x)] if x.islower() else upper_alph[
25 - upper_alph.index(x)] if x.isupper() else x, message))
def fnxor(message):
return "".join([chr((ord(letter) ^ ord(fn))) for letter, fn in zip(message, cycle("62601"))])
def encrypt_message(crypt):
def decorator(func):
def inner(*args, **kwargs):
match crypt:
case Crypts.rot13:
return ROT13(func(*args, **kwargs))
case Crypts.atbash:
return atbash(func(*args, **kwargs))
case Crypts.fnxor:
return fnxor(func(*args, **kwargs))
return inner
return decorator
=======================================================================
   Честито! Ти успя да видиш резултатите си преди останалите плебеи:
      Брой верни отговори: 25
      Брой получени точки: 29
=======================================================================
.......
----------------------------------------------------------------------
Ran 7 tests in 0.071s

OK
Александър Сариков
  • Коректно
  • 7 успешни тест(а)
  • 0 неуспешни тест(а)
Александър Сариков
def encrypt_message(alg):
def decorator_manager(func):
def rot13(*args, **kwargs):
rules = str.maketrans(
'ABCDEFGHIJKLMabcdefghijklmNOPQRSTUVWXYZnopqrstuvwxyz',
'NOPQRSTUVWXYZnopqrstuvwxyzABCDEFGHIJKLMabcdefghijklm')
return str(func(*args, **kwargs)).translate(rules)
def atbash(*args, **kwargs):
rules = str.maketrans(
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
'ZYXWVUTSRQPONMLKJIHGFEDCBAzyxwvutsrqponmlkjihgfedcba')
return str(func(*args, **kwargs)).translate(rules)
# Unused extended version
def atbash2(*args, **kwargs):
input = func(*args, **kwargs)
n = len(input)
result = ''
for i in range(n):
i_to_ord = ord(input[i])
if (ord('a') <= i_to_ord <= ord('z')):
char_index = ord('a') + ord('z') - i_to_ord
result += chr(char_index)
elif (ord('A') <= i_to_ord <= ord('Z')):
char_index = ord('A') + ord('Z') - i_to_ord
result += chr(char_index)
else:
result += input[i]
return result
def fn_xor(*args, **kwargs):
input = func(*args, **kwargs)
KEY = '61839'
key_length = len(KEY)
input_length = len(input)
result = ''
i = 0
while i < input_length:
result += chr(ord(input[i]) ^ ord(KEY[i % key_length]))
i += 1
return result
match alg:
case 'ROT-13':
return rot13
case 'ATBASH':
return atbash
case 'FN-XOR':
return fn_xor
case _:
return fn_xor
return decorator_manager
=======================================================================
   Честито! Ти успя да видиш резултатите си преди останалите плебеи:
      Брой верни отговори: 16
      Брой получени точки: 18
=======================================================================
.......
----------------------------------------------------------------------
Ran 7 tests in 0.070s

OK
Назифе Алиджик
  • Некоректно
  • 4 успешни тест(а)
  • 3 неуспешни тест(а)
Назифе Алиджик
def encrypt_message(cipher_type):
def log_result(func):
def inner(*args, **kwargs):
if cipher_type == 'ROT-13':
return encrypt_rot_13(func(*args, **kwargs))
elif cipher_type == 'ATBASH':
return encrypt_atbash(func(*args, **kwargs))
elif cipher_type == 'FN-XOR':
return encrypt_fn_xor(func(*args, **kwargs))
return inner
return log_result
def encrypt_atbash(message):
alphabet_table = {'A': 'Z', 'B': 'Y', 'C': 'X', 'D': 'W', 'E': 'V', 'F': 'U', 'G': 'T', 'H': 'S', 'I': 'R', 'J': 'Q', 'K': 'P', 'L': 'O', 'M': 'N', 'N': 'M', 'O': 'L',
'P': 'K', 'Q': 'J', 'R': 'I', 'S': 'H', 'T': 'G', 'U': 'F', 'V': 'E', 'W': 'D', 'X': 'C', 'Y': 'B', 'Z': 'A',
'a': 'z', 'b': 'y', 'c': 'x', 'd': 'w', 'e': 'v', 'f': 'u', 'g': 't', 'h': 's', 'i': 'r', 'j': 'q', 'k': 'p', 'l': 'o', 'm': 'n', 'n': 'm', 'o': 'l',
'p': 'k', 'q': 'j', 'r': 'i', 's': 'h', 't': 'g', 'u': 'f', 'v': 'e', 'w': 'd', 'x': 'x', 'y': 'b', 'z': 'a'}
cipher = ''
for letter in message:
if letter in alphabet_table:
cipher += alphabet_table[letter]
else:
cipher += letter
return cipher
def encrypt_rot_13(message):
result = ""
for letter in message:
c = ord(letter)
if c >= ord('a') and c <= ord('z'):
if c > ord('m'):
c -= 13
else:
c += 13
elif c >= ord('A') and c <= ord('Z'):
if c > ord('M'):
c -= 13
else:
c += 13
result += chr(c)
return result
def encrypt_fn_xor(message):
fn_key = '62598'
cipher = ''
for index, letter in enumerate(message):
cipher += chr(ord(letter) ^ ord(fn_key[index % 5]))
return cipher
=======================================================================
   Честито! Ти успя да видиш резултатите си преди останалите плебеи:
      Брой верни отговори: 19
      Брой получени точки: 22
=======================================================================
.FFF...
======================================================================
FAIL: test_atbash_empty_args (test.TestEncryptMessage)
Test for all chars in ATBASH with a function with empty args
----------------------------------------------------------------------
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: 'zyxwvutsrqponmlkjihgfedxbaZYXWVUTSRQPONMLKJIHGFEDCBA0123456789' != 'zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA0123456789'
- zyxwvutsrqponmlkjihgfedxbaZYXWVUTSRQPONMLKJIHGFEDCBA0123456789
?                        ^
+ zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA0123456789
?                        ^


======================================================================
FAIL: test_atbash_is_inverse (test.TestEncryptMessage)
Test that the ATBASH encryption is it's own inverse
----------------------------------------------------------------------
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: 'abxdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' != 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
- abxdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
?   ^
+ abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
?   ^


======================================================================
FAIL: test_atbash_with_args (test.TestEncryptMessage)
Test for all chars in ATBASH with a function with non-empty args
----------------------------------------------------------------------
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: 'zyxwvutsrqponmlkjihgfedxba, ZYXWVUTSRQPONMLKJIHGFEDCBA, 0123456789!' != 'zyxwvutsrqponmlkjihgfedcba, ZYXWVUTSRQPONMLKJIHGFEDCBA, 0123456789!'
- zyxwvutsrqponmlkjihgfedxba, ZYXWVUTSRQPONMLKJIHGFEDCBA, 0123456789!
?                        ^
+ zyxwvutsrqponmlkjihgfedcba, ZYXWVUTSRQPONMLKJIHGFEDCBA, 0123456789!
?                        ^


----------------------------------------------------------------------
Ran 7 tests in 0.081s

FAILED (failures=3)
Харут Партамиан
  • Коректно
  • 7 успешни тест(а)
  • 0 неуспешни тест(а)
Харут Партамиан
def encrypt_message(encryption_code):
def inner_decorator(func):
def wrapper(*args):
lower_alphabet = list(map(chr, range(97, 123)))
upper_alphabet = list(map(chr, range(65, 91)))
faculty_number = "62560"
encrypted_message = ""
match encryption_code:
case "ROT-13":
for char in func(*args):
if char in upper_alphabet:
encrypted_message += upper_alphabet[(upper_alphabet.index(char) + 13) % 26]
elif char in lower_alphabet:
encrypted_message += lower_alphabet[(lower_alphabet.index(char) + 13) % 26]
else:
encrypted_message += char
return encrypted_message
case "ATBASH":
for char in func(*args):
if char in upper_alphabet:
encrypted_message += upper_alphabet[25 - upper_alphabet.index(char)]
elif char in lower_alphabet:
encrypted_message += lower_alphabet[25 - lower_alphabet.index(char)]
else:
encrypted_message += char
return encrypted_message
case "FN-XOR":
for idx, char in enumerate(func(*args)):
faculty_number_digit = faculty_number[idx % 5]
encrypted_message += chr(ord(faculty_number_digit) ^ ord(char))
return encrypted_message
return wrapper
return inner_decorator
=======================================================================
   Честито! Ти успя да видиш резултатите си преди останалите плебеи:
      Брой верни отговори: 13
      Брой получени точки: 15
=======================================================================
.......
----------------------------------------------------------------------
Ran 7 tests in 0.072s

OK
Йоанна Кръстева
  • Коректно
  • 7 успешни тест(а)
  • 0 неуспешни тест(а)
Йоанна Кръстева
encryptor = {'a': 'n', 'b': 'o', 'c': 'p',
'd': 'q', 'e': 'r', 'f': 's',
'g': 't', 'h': 'u', 'i': 'v',
'j': 'w', 'k': 'x', 'l': 'y',
'm': 'z', 'n': 'a', 'o': 'b',
'p': 'c', 'q': 'd', 'r': 'e',
's': 'f', 't': 'g', 'u': 'h',
'v': 'i', 'w': 'j', 'x': 'k',
'y': 'l', 'z': 'm'}
def encrypt_message(flag):
def result(func):
def inner(*args, **kwargs):
if flag == 'ROT-13':
return rot_encryptor(func(*args, **kwargs))
elif flag == 'ATBASH':
return at_bash_encryptor(func(*args, **kwargs))
elif flag == 'FN-XOR':
return fn_xor_encryptor(func(*args, **kwargs))
return inner
return result
def rot_encryptor(to_encrypt):
encrypted = ''
for letter in to_encrypt:
if letter.islower():
encrypted += encryptor.get(letter)
if letter.isupper():
letter = letter.lower()
encrypted += encryptor.get(letter).capitalize()
if letter not in encryptor:
encrypted += letter
return encrypted
def at_bash_encryptor(to_encrypt):
encrypted = ''
for i in range(0, len(to_encrypt)):
left_value = ord(to_encrypt[i])
if ord('a') <= left_value <= ord('z'):
right_value = ord('a') + ord('z') - left_value
encrypted = encrypted + chr(right_value)
elif ord('A') <= left_value <= ord('Z'):
right_value = ord('A') + ord('Z') - left_value
encrypted = encrypted + chr(right_value)
else:
encrypted = encrypted + to_encrypt[i]
return encrypted
def fn_xor_encryptor(to_encrypt):
faculty_number = '62578'
encrypted = ''
for index, letter in enumerate(to_encrypt):
xor_num = ord(letter) ^ ord(faculty_number[index % 5])
encrypted += chr(xor_num)
return encrypted
=======================================================================
   Честито! Ти успя да видиш резултатите си преди останалите плебеи:
      Брой верни отговори: 22
      Брой получени точки: 25
=======================================================================
.......
----------------------------------------------------------------------
Ran 7 tests in 0.075s

OK
Стилиян Иванов
  • Коректно
  • 7 успешни тест(а)
  • 0 неуспешни тест(а)
Стилиян Иванов
def encrypt_message(algorithm):
def decorator(func):
def return_string(*args):
result = func(*args)
if algorithm == 'ROT-13':
result = '' . join([chr(ord(letter) + 13 if ord(letter.lower()) + 13 <= ord('z')
else ord(letter) - 13) if 'a' <= letter.lower() <= 'z'
else letter for letter in result])
elif algorithm == 'ATBASH':
result = '' . join([chr(ord('a') + ord('z') - ord(letter)) if 'a' <= letter <= 'z'
else chr(ord('A') + ord('Z') - ord(letter)) if 'A' <= letter <= 'Z'
else letter for letter in result])
elif algorithm == 'FN-XOR':
key = '7MI0600083'
result = '' . join([chr(ord(char) ^ ord(key[index % len(key)])) for index, char in enumerate(result)])
return result
return return_string
return decorator
=======================================================================
   Честито! Ти успя да видиш резултатите си преди останалите плебеи:
      Брой верни отговори: 26
      Брой получени точки: 30
=======================================================================
.......
----------------------------------------------------------------------
Ran 7 tests in 0.070s

OK
Антоан Ивайлов
  • Коректно
  • 7 успешни тест(а)
  • 0 неуспешни тест(а)
Антоан Ивайлов
def is_lowercase_letter(letter):
return 'a' <= letter <= 'z'
def is_uppercase_letter(letter):
return 'A' <= letter <= 'Z'
def apply_rot_13_encrypt(letter):
ROT_13_JUMP = 13 # Alternative way may be to use double dict
if is_lowercase_letter(letter):
letter = chr(ord(letter) + ROT_13_JUMP)
if not is_lowercase_letter(letter): # Return to the valid chars input if we have jumped over them
letter = chr(ord(letter) - 2 * ROT_13_JUMP)
elif is_uppercase_letter(letter): # Needs to be a valid letter in order for the algorithm to take place
letter = chr(ord(letter) + ROT_13_JUMP)
if not is_uppercase_letter(letter):
letter = chr(ord(letter) - 2 * ROT_13_JUMP)
return letter
def apply_atbash_encrypt(letter):
# Algorithm works based of the middle of the sequence, so we should add up both sides and extract the 'middle'
if is_lowercase_letter(letter):
letter = chr(ord('a') + ord('z') - ord(letter))
elif is_uppercase_letter(letter):
letter = chr(ord('A') + ord('Z') - ord(letter))
return letter
def apply_fn_xor_encrypt(letter, curr_iteration_char_index):
FACULTY_NUM = '7MI0600129'
encrypted_letter = chr(ord(letter) ^ ord(FACULTY_NUM[curr_iteration_char_index]))
curr_iteration_char_index += 1
if curr_iteration_char_index == len(FACULTY_NUM):
curr_iteration_char_index = 0
return encrypted_letter, curr_iteration_char_index
def encrypt_letter(letter, encryption_algorithm, fn_char_index=None):
if encryption_algorithm == 'ROT-13':
return apply_rot_13_encrypt(letter)
elif encryption_algorithm == 'ATBASH':
return apply_atbash_encrypt(letter)
else:
return apply_fn_xor_encrypt(letter, fn_char_index)
def encrypt_message(encryption_algorithm):
def read_and_encode_message(raw_message_function):
def cipher_message(*args):
raw_message = raw_message_function(*args)
encrypted_message = ''
fn_xor_index = 0
for letter in raw_message:
'''Second FN-XOR check needed, otherwise no mutability will be available in our encryption algos. In this
example we could theoretically mix encryption algorithms.'''
if encryption_algorithm == 'FN-XOR':
masked_letter, fn_xor_index = encrypt_letter(letter, encryption_algorithm, fn_xor_index)
else:
masked_letter = encrypt_letter(letter, encryption_algorithm)
encrypted_message += masked_letter
return encrypted_message
return cipher_message
return read_and_encode_message
=======================================================================
   Честито! Ти успя да видиш резултатите си преди останалите плебеи:
      Брой верни отговори: 23
      Брой получени точки: 27
=======================================================================
.......
----------------------------------------------------------------------
Ran 7 tests in 0.073s

OK
Айше Джинджи
  • Коректно
  • 7 успешни тест(а)
  • 0 неуспешни тест(а)
Айше Джинджи
from functools import wraps
import string
FN = '62470'
LETTERS_LOWERCASE = list(string.ascii_lowercase)
LETTERS_UPPERCASE = list(string.ascii_uppercase)
def rotate_letter(letter):
if letter in LETTERS_LOWERCASE:
index = (LETTERS_LOWERCASE.index(letter) + 13) % len(LETTERS_LOWERCASE)
return LETTERS_LOWERCASE[index]
if letter in LETTERS_UPPERCASE:
index = (LETTERS_UPPERCASE.index(letter) + 13) % len(LETTERS_UPPERCASE)
return LETTERS_UPPERCASE[index]
return letter
def rot_13(message):
return ''.join([rotate_letter(letter) for letter in message])
def mirror_letter(letter):
if letter in LETTERS_LOWERCASE:
index = len(LETTERS_LOWERCASE) - LETTERS_LOWERCASE.index(letter) - 1
return LETTERS_LOWERCASE[index]
if letter in LETTERS_UPPERCASE:
index = len(LETTERS_UPPERCASE) - LETTERS_UPPERCASE.index(letter) - 1
return LETTERS_UPPERCASE[index]
return letter
def atbash(message):
return ''.join([mirror_letter(letter) for letter in message])
def xor_letter(letter, index):
respective_index = index % len(FN)
respective_symbol = FN[respective_index]
return chr(ord(letter) ^ ord(respective_symbol))
def fn_xor(message):
return ''.join([xor_letter(message[index], index) for index in range(len(message))])
def encrypt_message(encryption_method):
def decorate(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
if encryption_method == 'ROT-13':
return rot_13(fn(*args, **kwargs))
elif encryption_method == 'ATBASH':
return atbash(fn(*args, **kwargs))
elif encryption_method == 'FN-XOR':
return fn_xor(fn(*args, **kwargs))
return wrapper
return decorate
=======================================================================
   Честито! Ти успя да видиш резултатите си преди останалите плебеи:
      Брой верни отговори: 22
      Брой получени точки: 25
=======================================================================
.......
----------------------------------------------------------------------
Ran 7 tests in 0.075s

OK
Петър Петров
  • Коректно
  • 7 успешни тест(а)
  • 0 неуспешни тест(а)
Петър Петров
def encrypt_message(encrypt_method):
def rot_13(original_func):
def encrypt_rot_13(*args):
rot_13_encrypt = str.maketrans(
'ABCDEFGHIJKLMabcdefghijklmNOPQRSTUVWXYZnopqrstuvwxyz',
'NOPQRSTUVWXYZnopqrstuvwxyzABCDEFGHIJKLMabcdefghijklm')
return original_func(*args).translate(rot_13_encrypt)
return encrypt_rot_13
def atbash(original_func):
def encrypt_atbash(*args):
atbash_encrypt = str.maketrans(
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
'ZYXWVUTSRQPONMLKJIHGFEDCBAzyxwvutsrqponmlkjihgfedcba')
return original_func(*args).translate(atbash_encrypt)
return encrypt_atbash
def fn_xor(original_func):
def encrypt_fn_xor(*args):
result = ''
def next_fn():
key = '62373'
while True:
for num in key:
yield num
for element, fn_number in zip(original_func(*args), next_fn()):
result += chr(ord(element) ^ ord(fn_number))
return result
return encrypt_fn_xor
return rot_13 if encrypt_method == 'ROT-13' else atbash if encrypt_method == 'ATBASH' else fn_xor
=======================================================================
   Честито! Ти успя да видиш резултатите си преди останалите плебеи:
      Брой верни отговори: 14
      Брой получени точки: 16
=======================================================================
.......
----------------------------------------------------------------------
Ran 7 tests in 0.073s

OK
Теодора Петкова
  • Коректно
  • 7 успешни тест(а)
  • 0 неуспешни тест(а)
Теодора Петкова
def add13(letter):
new_symbol = chr(ord(letter) + 13)
if new_symbol > 'z':
diff = ord(new_symbol) - ord('z')
new_symbol = chr(ord('a') + diff - 1)
return new_symbol
def rot_13(message):
result = ""
for symbol in message:
if 'a' <= symbol <= 'z':
new_symbol = add13(symbol)
elif 'A' <= symbol <= 'Z':
new_symbol = add13(symbol.lower()).upper()
else:
new_symbol = symbol
result += new_symbol
return result
def atbash(message):
key_table = {'A': 'Z',
'B': 'Y',
'C': 'X',
'D': 'W',
'E': 'V',
'F': 'U',
'G': 'T',
'H': 'S',
'I': 'R',
'J': 'Q',
'K': 'P',
'L': 'O',
'M': 'N',
'N': 'M',
'O': 'L',
'P': 'K',
'Q': 'J',
'R': 'I',
'S': 'H',
'T': 'G',
'U': 'F',
'V': 'E',
'W': 'D',
'X': 'C',
'Y': 'B',
'Z': 'A'}
result = ""
for symbol in message:
if 'a' <= symbol <= 'z':
new_symbol = key_table[symbol.upper()].lower()
elif 'A' <= symbol <= 'Z':
new_symbol = key_table[symbol]
else:
new_symbol = symbol
result += new_symbol
return result
def fn_xor(message):
xor_key = '62538'
result = ""
i = 0
for symbol in message:
# print(f" {symbol} xor {xor_key[i]} is {ord(symbol) ^ ord(xor_key[i])}")
new_symbol = chr(ord(symbol) ^ ord(xor_key[i]))
result += new_symbol
i += 1
if i >= len(xor_key):
i = 0
return result
def encrypt_message(type_of_encrytion):
def decorator(func):
def encryption(*arg, **kwargs):
if type_of_encrytion == 'ROT-13':
# print('rot-13 encrypt: ')
return rot_13(func(*arg, **kwargs))
elif type_of_encrytion == 'ATBASH':
# print('atbash encrypt: ')
return atbash(func(*arg, **kwargs))
elif type_of_encrytion == 'FN-XOR':
# print('fn-xor encrypt: ')
return fn_xor(func(*arg, **kwargs))
return encryption
return decorator
=======================================================================
   Честито! Ти успя да видиш резултатите си преди останалите плебеи:
      Брой верни отговори: 16
      Брой получени точки: 18
=======================================================================
.......
----------------------------------------------------------------------
Ran 7 tests in 0.073s

OK
Таня Сейкова
  • Коректно
  • 7 успешни тест(а)
  • 0 неуспешни тест(а)
Таня Сейкова
def encrypt_ROT_13(txt):
result = ""
small_letters = list(map(chr, range(ord('a'), ord('z')+1)))
capital_letters = list(map(chr, range(ord('A'), ord('Z')+1)))
for letter in txt:
if letter in small_letters:
ind = small_letters.index(letter)
ind = (ind + 13) % 26
result += small_letters[ind]
continue
if letter in capital_letters:
ind = capital_letters.index(letter)
ind = (ind + 13) % 26
result += capital_letters[ind]
continue
result += letter
return result
def encrypt_ATBASH(txt):
result = ""
small_letters = list(map(chr, range(ord('a'), ord('z')+1)))
capital_letters = list(map(chr, range(ord('A'), ord('Z')+1)))
for letter in txt:
if letter in small_letters:
ind = small_letters.index(letter)
result += small_letters[26 - 1 - ind]
continue
if letter in capital_letters:
ind = capital_letters.index(letter)
result += capital_letters[26 - 1 - ind]
continue
result += letter
return result
def encrypt_FN_XOR(txt, key_fn):
result = ""
key_ind = 0
len_key = len(key_fn)
for letter in txt:
if key_ind >= len_key:
key_ind = 0
result += chr(ord(letter) ^ ord(key_fn[key_ind]))
key_ind += 1
return result
def encrypt_message(method):
def encrypt(fnc):
def wrapper(*args,**kwargs):
if method == 'ROT-13':
return encrypt_ROT_13(fnc(*args,**kwargs))
elif method == 'ATBASH':
return encrypt_ATBASH(fnc(*args,**kwargs))
else:
key_fn = "62472"
return encrypt_FN_XOR(fnc(*args,**kwargs), key_fn)
return wrapper
return encrypt
=======================================================================
   Честито! Ти успя да видиш резултатите си преди останалите плебеи:
      Брой верни отговори: 16
      Брой получени точки: 18
=======================================================================
.......
----------------------------------------------------------------------
Ran 7 tests in 0.073s

OK
Надежда Панделиева
  • Коректно
  • 7 успешни тест(а)
  • 0 неуспешни тест(а)
Надежда Панделиева
import codecs
import string
fn='62468'
# leave it to see that I am a thinker
def rot(word):
letters = list(string.ascii_lowercase)
rotated = letters[13:] + letters[:13]
ans = ''
for w in word:
if w.isupper():
if w.lower() in letters:
ans += rotated[letters.index(w.lower())].upper()
else:
ans += w
else:
if w in letters:
ans += rotated[letters.index(w)]
else:
ans += w
return ans
def rot_13(message):
return codecs.encode(message, 'rot_13')
def atbash(message):
letters = list(string.ascii_lowercase)
opposite = letters[::-1]
ans = ""
for w in message:
if w.isupper():
if w.lower() in letters:
ans += opposite[letters.index(w.lower())].upper()
else:
ans += w
else:
if w in letters:
ans += opposite[letters.index(w)]
else:
ans += w
return ans
def fn_xor(message):
additional = int(len(message) // len(fn)) +1
return ''.join([chr(ord(w)^ord(k)) for w,k in zip(message,fn*additional)])
def encrypt_message(method):
def decorator(func):
def wrapper(*args):
if method == 'ROT-13':
return rot_13(func(*args))
elif method == 'ATBASH':
return atbash(func(*args))
elif method == 'FN-XOR':
return fn_xor(func(*args))
return wrapper
return decorator
=======================================================================
   Честито! Ти успя да видиш резултатите си преди останалите плебеи:
      Брой верни отговори: 17
      Брой получени точки: 20
=======================================================================
.......
----------------------------------------------------------------------
Ran 7 tests in 0.077s

OK
Александра Павлова
  • Коректно
  • 7 успешни тест(а)
  • 0 неуспешни тест(а)
Александра Павлова
alphabet = 'abcdefghijklmnopqrstuvwxyz'
upper_alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def encrypt_message(crypt_method):
if crypt_method == 'ROT-13':
func = rot_13
elif crypt_method == 'ATBASH':
func = atbash
elif crypt_method == 'FN-XOR':
func = fn_xor
def decorator(function):
def wrapper(*args):
return func(function(*args))
return wrapper
return decorator
def rot_13(message):
encrypted_message = ''
for ch in message:
if 64 < ord(ch) < 78:
encrypted_message += chr(ord(ch) + 13)
elif 77 < ord(ch) < 91:
encrypted_message += chr(ord(ch) - 13)
elif 96 < ord(ch) < 110:
encrypted_message += chr(ord(ch) + 13)
elif 109 < ord(ch) < 123:
encrypted_message += chr(ord(ch) - 13)
else:
encrypted_message += ch
return encrypted_message
def atbash(message):
encrypted_message = ''
for ch in message:
if 64 < ord(ch) < 91:
trans = str.maketrans(upper_alphabet, upper_alphabet[::-1], ' ')
encrypted_message += ch.translate(trans)
elif 96 < ord(ch) < 123:
trans = str.maketrans(alphabet, alphabet[::-1], ' ')
ch.translate(trans)
encrypted_message += ch.translate(trans)
else:
encrypted_message += ch
return encrypted_message
def fn_xor(message):
key = '31641'
encrypted_message = ''
index = 0
for ch in str(message):
if index > len(key) - 1:
index = 0
xor_num = ord(ch) ^ ord(key[index])
encrypted_message += chr(xor_num)
index += 1
return encrypted_message
@encrypt_message('ROT-13')
def michael_bolton():
return 'This is the tale of Captain Jack Sparrow!'
print(michael_bolton())
# Guvf vf gur gnyr bs Pncgnva Wnpx Fcneebj!
@encrypt_message('ATBASH')
def michael_bolton(person):
return f'This is the tale of {person}!'
print(michael_bolton('Captain Jack Sparrow'))
# Gsrh rh gsv gzov lu Xzkgzrm Qzxp Hkziild!
@encrypt_message('FN-XOR')
def michael_bolton(person, description):
return f'This is the tale of {person}, {description}!'
print(michael_bolton('Captain Jack Sparrow', 'pirate so brave of the Seven Seas'))
# bYZC_BDYSGQ]S\VuPCDP__zPUZcAWCA_FCYCWEVBYQBP@T_WE[UeTEU_bVQB
Guvf vf gur gnyr bs Pncgnva Wnpx Fcneebj!
Gsrh rh gsv gzov lu Xzkgzrm Qzxp Hkziild!
gY_GZB@YVBU]VYRpPF@PZ_~PPZgARCD[FF]CRESB\TFPET[WE^Q`T@Q_bSUB



=======================================================================
   Честито! Ти успя да видиш резултатите си преди останалите плебеи:
      Брой верни отговори: 11
      Брой получени точки: 13
=======================================================================
.......
----------------------------------------------------------------------
Ran 7 tests in 0.073s

OK
Ангел Марински
  • Коректно
  • 7 успешни тест(а)
  • 0 неуспешни тест(а)
Ангел Марински
import string
from functools import wraps
FN = '62469'
ALPHABET = list(string.ascii_lowercase)
def xor_letter(letter, index):
digit = FN[index % len(FN)]
return chr(ord(letter) ^ ord(digit))
def rotate13(letter):
if letter.lower() not in ALPHABET:
return letter
idx = (ALPHABET.index(letter.lower()) + 13) % len(ALPHABET)
if letter in string.ascii_uppercase:
return ALPHABET[idx].upper()
return ALPHABET[idx]
def vice_versa_method(letter):
if letter.lower() not in ALPHABET:
return letter
idx = len(ALPHABET) - (ALPHABET.index(letter.lower()) + 1)
if letter in string.ascii_uppercase:
return ALPHABET[idx].upper()
return ALPHABET[idx]
def fn_xor(msg):
result = ''
for index in range(len(msg)):
result += xor_letter(msg[index], index)
return result
def rot_13(msg):
result = ''
for letter in msg:
result += rotate13(letter)
return result
def atbash(msg):
result = ''
for letter in msg:
result += vice_versa_method(letter)
return result
def encrypt_message(method):
def decorator(fn):
@wraps(fn)
def wrapper(*args, ** kwargs):
if method == 'FN-XOR':
return fn_xor(fn(*args, **kwargs))
elif method == 'ROT-13':
return rot_13(fn(*args, **kwargs))
elif method == 'ATBASH':
return atbash(fn(*args, **kwargs))
else:
raise Exception("Invalid function name")
return wrapper
return decorator
=======================================================================
   Честито! Ти успя да видиш резултатите си преди останалите плебеи:
      Брой верни отговори: 17
      Брой получени точки: 20
=======================================================================
.......
----------------------------------------------------------------------
Ran 7 tests in 0.075s

OK