Created
June 4, 2021 13:40
-
-
Save frodo821/52db32a8b04f62f15b1eaf0cb3857aba to your computer and use it in GitHub Desktop.
ヴィジュネル暗号(Vigenère cipher)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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