mirror of
https://github.com/Xevion/exercism.git
synced 2025-12-06 03:15:01 -06:00
simple cipher exercise changed imports, modifed alphabet name
This commit is contained in:
@@ -1,32 +1,26 @@
|
|||||||
from string import ascii_lowercase as alphabet
|
from string import ascii_lowercase as abc
|
||||||
from pprint import PrettyPrinter
|
from random import shuffle
|
||||||
import random
|
|
||||||
print = PrettyPrinter().pprint
|
|
||||||
|
|
||||||
class Cipher(object):
|
class Cipher(object):
|
||||||
def __init__(self, key=None):
|
def __init__(self, key=None):
|
||||||
if key:
|
if key:
|
||||||
self.key = ''.join(dict.fromkeys(self.key)) # Key with repeated characters is completely useless
|
self.key = ''.join(dict.fromkeys(self.key)) # Key with repeated characters is completely useless
|
||||||
elif not key:
|
elif not key:
|
||||||
self.key = list(alphabet)
|
self.key = list(abc)
|
||||||
random.shuffle(self.key)
|
shuffle(self.key)
|
||||||
self.key = ''.join(self.key)
|
self.key = ''.join(self.key)
|
||||||
|
|
||||||
key_values = [self.keyvalue(i) for i in range(len(self.key))]
|
key_values = [self.keyvalue(i) for i in range(len(self.key))]
|
||||||
self.key_alphabets = [(alphabet[index:] + alphabet[: index]) for index in key_values]
|
self.key_alphabets = [(abc[index:] + abc[: index]) for index in key_values]
|
||||||
|
|
||||||
def encode(self, text):
|
def encode(self, text):
|
||||||
return ''.join(self.key_alphabets[index][alphabet.find(char)]
|
return ''.join(self.key_alphabets[index][abc.find(char)]
|
||||||
for index, char in enumerate(text.lower()))
|
for index, char in enumerate(text.lower()))
|
||||||
|
|
||||||
def decode(self, text):
|
def decode(self, text):
|
||||||
return ''.join(alphabet[self.key_alphabets[index].find(char)]
|
return ''.join(abc[self.key_alphabets[index].find(char)]
|
||||||
for index, char in enumerate(text.lower()))
|
for index, char in enumerate(text.lower()))
|
||||||
|
|
||||||
# Gets the shifting value of the key at the index specified
|
# Gets the shifting value of the key at the index specified
|
||||||
def keyvalue(self, index):
|
def keyvalue(self, index):
|
||||||
return alphabet.find(self.key[index % len(self.key)])
|
return abc.find(self.key[index % len(self.key)])
|
||||||
|
|
||||||
random.seed(0)
|
|
||||||
c = Cipher()
|
|
||||||
print(c.decode(c.encode('Hello World')))
|
|
||||||
Reference in New Issue
Block a user