Aufgabe 2 Codewars
This commit is contained in:
parent
890bad0fda
commit
65e0b68e47
3
README.me
Normal file
3
README.me
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
Codewars
|
||||||
|
Aufgabe 1 Snail: https://www.codewars.com/kata/521c2db8ddc89b9b7a0000c1
|
||||||
|
Aufgabe 2 Vigenère Cipher Helper: https://www.codewars.com/kata/52d1bd3694d26f8d6e0000d3
|
||||||
65
src/codewars/vigenere_cipher_helper.py
Normal file
65
src/codewars/vigenere_cipher_helper.py
Normal file
@ -0,0 +1,65 @@
|
|||||||
|
class VigenereCipher(object):
|
||||||
|
def __init__(self, key, alphabet):
|
||||||
|
self.key = key
|
||||||
|
self.alphabet = alphabet
|
||||||
|
|
||||||
|
def encode(self, text):
|
||||||
|
key = (self.key * ((len(text) // len(self.key)) + 1))[: len(text)]
|
||||||
|
|
||||||
|
result = []
|
||||||
|
idx = 0
|
||||||
|
|
||||||
|
for text_char in text:
|
||||||
|
if text_char not in self.alphabet:
|
||||||
|
result.append(text_char)
|
||||||
|
idx += 1
|
||||||
|
elif (
|
||||||
|
self.alphabet.index(text_char) + self.alphabet.index(key[idx])
|
||||||
|
<= len(self.alphabet) - 1
|
||||||
|
):
|
||||||
|
result.append(
|
||||||
|
self.alphabet[
|
||||||
|
self.alphabet.index(text_char) + self.alphabet.index(key[idx])
|
||||||
|
]
|
||||||
|
)
|
||||||
|
idx += 1
|
||||||
|
else:
|
||||||
|
result.append(
|
||||||
|
self.alphabet[
|
||||||
|
self.alphabet.index(text_char)
|
||||||
|
+ self.alphabet.index(key[idx])
|
||||||
|
- len(self.alphabet)
|
||||||
|
]
|
||||||
|
)
|
||||||
|
idx += 1
|
||||||
|
|
||||||
|
return "".join(result)
|
||||||
|
|
||||||
|
def decode(self, text):
|
||||||
|
key = (self.key * ((len(text) // len(self.key)) + 1))[: len(text)]
|
||||||
|
|
||||||
|
result = []
|
||||||
|
idx = 0
|
||||||
|
|
||||||
|
for text_char in text:
|
||||||
|
if text_char not in self.alphabet:
|
||||||
|
result.append(text_char)
|
||||||
|
idx += 1
|
||||||
|
elif self.alphabet.index(text_char) - self.alphabet.index(key[idx]) >= 0:
|
||||||
|
result.append(
|
||||||
|
self.alphabet[
|
||||||
|
self.alphabet.index(text_char) - self.alphabet.index(key[idx])
|
||||||
|
]
|
||||||
|
)
|
||||||
|
idx += 1
|
||||||
|
else:
|
||||||
|
result.append(
|
||||||
|
self.alphabet[
|
||||||
|
self.alphabet.index(text_char)
|
||||||
|
- self.alphabet.index(key[idx])
|
||||||
|
+ len(self.alphabet)
|
||||||
|
]
|
||||||
|
)
|
||||||
|
idx += 1
|
||||||
|
|
||||||
|
return "".join(result)
|
||||||
Loading…
x
Reference in New Issue
Block a user