Skip to content

Instantly share code, notes, and snippets.

@frodo821
Created June 4, 2021 13:40
Show Gist options
  • Save frodo821/52db32a8b04f62f15b1eaf0cb3857aba to your computer and use it in GitHub Desktop.
Save frodo821/52db32a8b04f62f15b1eaf0cb3857aba to your computer and use it in GitHub Desktop.
ヴィジュネル暗号(Vigenère cipher)
from itertools import cycle
a = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
chrs = cycle('ZABCDEFGHIJKLMNOPQRSTUVWXY')
table = {l: {a[i-1]: c for c, i in zip(chrs, range(26)) if i != 0} for l in a}
def encode(message: str, key: str) -> str:
return ''.join(
c if u else c.lower() for c, u in (
(table[k.upper()].get(m.upper(), m.upper()), m.isupper()) for m, k in zip(message, cycle(key))
)
)
def decode(message: str, key: str) -> str:
return ''.join(
c if u else c.lower() for c, u in (
(({v: k for k, v in table[k.upper()].items()}).get(m.upper(), m.upper()), m.isupper()) for m, k in zip(message, cycle(key))
)
)
if __name__ == '__main__':
encode_key = "itmakesmehappy"
message = "Hello, coins!!"
assert "Pxxly, ospnh!!" == encode(message, encode_key)
assert message == decode(encode(message, encode_key), encode_key)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment