-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathVigenere_Cipher_Helper.py
More file actions
65 lines (53 loc) · 2.48 KB
/
Vigenere_Cipher_Helper.py
File metadata and controls
65 lines (53 loc) · 2.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import unittest
class VigenereCipher(object):
def __init__(self, key, alphabet):
self.key = key
self.alphabet = alphabet
def encode(self, text):
result = ""
key_len = len(self.key)
alphabet_len = len(self.alphabet)
key_index = 0
for char in text:
if char in self.alphabet:
char_index = self.alphabet.index(char)
key_char = self.key[key_index % key_len]
key_val = self.alphabet.index(key_char)
new_index = (char_index + key_val) % alphabet_len
result += self.alphabet[new_index]
else:
result += char
key_index += 1
return result
def decode(self, text):
result = ""
key_len = len(self.key)
alphabet_len = len(self.alphabet)
key_index = 0
for char in text:
if char in self.alphabet:
char_index = self.alphabet.index(char)
key_char = self.key[key_index % key_len]
key_val = self.alphabet.index(key_char)
new_index = (char_index - key_val) % alphabet_len
result += self.alphabet[new_index]
else:
result += char
key_index += 1
return result
class TestVigenereCipher(unittest.TestCase):
def setUp(self):
abc = "abcdefghijklmnopqrstuvwxyz"
key = "password"
self.cipher = VigenereCipher(key, abc)
def test_sample_cases(self):
self.assertEqual(self.cipher.encode('codewars'), 'rovwsoiv', "Test de codificación 'codewars'")
self.assertEqual(self.cipher.decode('rovwsoiv'), 'codewars', "Test de decodificación 'rovwsoiv'")
self.assertEqual(self.cipher.encode('waffles'), 'laxxhsj', "Test de codificación 'waffles'")
self.assertEqual(self.cipher.decode('laxxhsj'), 'waffles', "Test de decodificación 'laxxhsj'")
self.assertEqual(self.cipher.encode('CODEWARS'), 'CODEWARS', "Test de codificación 'CODEWARS'")
self.assertEqual(self.cipher.decode('CODEWARS'), 'CODEWARS', "Test de decodificación 'CODEWARS'")
self.assertEqual(self.cipher.encode("it's a shift cipher!"), "xt'k o vwixl qzswej!", "Test con espacios y puntuación")
self.assertEqual(self.cipher.decode("xt'k o vwixl qzswej!"), "it's a shift cipher!", "Test de decodificación con espacios y puntuación")
if __name__ == '__main__':
unittest.main(verbosity=2)