Merge pull request 'Aufgabe 2 Codewars' (#3) from Aufgabe2 into master
Reviewed-on: #3 Sehr schön! Wen man wollte, könnte man encode und decode noch vereinfachen, weil sehr viel Code praktisch identisch ist. Sie unterscheiden sich ja fast nur durch ein - und ein +. Die Wartung des Codes würde durch das vereinfacht. Ist aber gut gelöst so!
This commit is contained in:
commit
a63ffeb7b6
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