Skip to content

Instantly share code, notes, and snippets.

@inesusvet
Created February 3, 2019 16:43
Show Gist options
  • Save inesusvet/1bd1e43ab0a1b5ed6840a236b89dcd5b to your computer and use it in GitHub Desktop.
Save inesusvet/1bd1e43ab0a1b5ed6840a236b89dcd5b to your computer and use it in GitHub Desktop.
Coding dojo in Minsk session result for 2019-02-03
"""
See https://www.codewars.com/kata/digital-cypher
"""
import itertools
import string
ABC = string.ascii_lowercase
def build_abc_map(abc):
"""
>>> build_abc_map('abc')
{'a': 1, 'c': 3, 'b': 2}
"""
result = {alpha: index for index, alpha in enumerate(abc, 1)}
return result
def encode(text, key):
"""
>>> encode("scout", 1939)
[20, 12, 18, 30, 21]
>>> encode("masterpiece", 1939)
[14, 10, 22, 29, 6, 27, 19, 18, 6, 12, 8]
"""
abc_dict = build_abc_map(ABC)
key_str = str(key)
infinite_key = itertools.cycle(key_str)
return [
abc_dict[char] + int(offset)
for char, offset in zip(text, infinite_key)
]
def encode_by_string(text, key_str):
"""
>>> encode_by_string("scout", "a")
'tdpvu'
"""
abc_dict = build_abc_map(ABC)
numeric_dict = {value: key for key, value in abc_dict.items()}
infinite_key = itertools.cycle(key_str)
return ''.join([
numeric_dict[(abc_dict[char] + abc_dict[offset]) % len(numeric_dict)]
for char, offset in zip(text, infinite_key)
])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment