1"""
2apr 1: nested for loops O(len(str) * len(pairs))
3apr 2: create a dict in 2 * O(len(pairs))
4then traverse string in O(len(str) * O(1))
5Total O(len(str) + len(pairs)), which should be better
6"""
7def plugboard(text, pairs):
8 result = ''
9 new_dict = {list(pairs[i])[0] : list(pairs[i])[1]
10 for i in range(len(pairs))}
11 new_dict.update({list(pairs[i])[1] : list(pairs[i])[0]
12 for i in range(len(pairs))})
13
14 for char in text:
15 if char in new_dict:
16 result = result + new_dict[char]
17 else: result = result + char
18 return result
19
20def rotor(text, code):
21 result = ''
22
23 for char in text:
24 if char != ' ':
25 result = result + code[char]
26 else: result = result + ' '
27
28 return result
29
30def enigma_encrypt(plugboard_position, rotor_position):
31
32 def encrypt(func):
33
34 def result_func(text):
35 return func(rotor(plugboard(text, plugboard_position),
36 rotor_position))
37 return result_func
38
39 return encrypt
40
41def enigma_decrypt(plugboard_position, rotor_position):
42
43 def encrypt(func):
44
45 def result_func(text):
46 reverse_rotor_position = {}
47
48 for key, value in rotor_position.items():
49 reverse_rotor_position.update({value : key})
50
51 return func(plugboard(rotor(text, reverse_rotor_position),
52 plugboard_position))
53 return result_func
54
55 return encrypt
.........
----------------------------------------------------------------------
Ran 9 tests in 0.001s
OK
Мартин Кузманов
29.10.2023 11:20С оглед на казаното по-горе, когато деля редове за напред ( които надминават конвенцията със 80 знака) трябва да приравня с аргумента на предходния ред.
|
29.10.2023 09:09
29.10.2023 09:09
29.10.2023 09:11