CMU Coding Bootcamp
at main 1.5 kB view raw
1def encodeSimpleCipher(s: str) -> str: 2 """ 3 Encode a string using this formula. 4 - s[i] = 2*i 5 - if 2*i > len(s), s[i] = (2*i) % len(s) 6 """ 7 encoded = list(s) 8 for i in range(len(s)): 9 j = (2 * i) % len(s) 10 cj = encoded[j] 11 encoded[j] = encoded[i] 12 encoded[i] = cj 13 return "".join(encoded) 14 15 16def decodeSimpleCipher(s: str) -> str: 17 """Decode a string encoded from encodeSimpleCipher""" 18 decoded = list(s) 19 for i in range(len(s) - 1, -1, -1): 20 j = (2 * i) % len(s) 21 cj = decoded[j] 22 decoded[j] = decoded[i] 23 decoded[i] = cj 24 return "".join(decoded) 25 26 27print("Testing encodeSimpleCipher()...", end="") 28assert encodeSimpleCipher("AB") == "BA" 29assert encodeSimpleCipher("ABC") == "ABC" 30assert encodeSimpleCipher("ABCD") == "BCDA" 31assert encodeSimpleCipher("ABCDEFGH") == "BCFGDEHA" 32assert encodeSimpleCipher("SECRET MESSAGE") == "MCE SSTSAEREEG" 33assert ( 34 encodeSimpleCipher("THIS IS A LONGER SECRET MESSAGE JUST FOR YOU!") 35 == "T SAENG SR MGARJ H U!SSTE TFECORIIEYSELUOOS" 36) 37print("Passed!") 38 39 40print("Testing decodeSimpleCipher()...", end="") 41assert decodeSimpleCipher("BA") == "AB" 42assert decodeSimpleCipher("ABC") == "ABC" 43assert decodeSimpleCipher("BCDA") == "ABCD" 44assert decodeSimpleCipher("BCFGDEHA") == "ABCDEFGH" 45assert decodeSimpleCipher("MCE SSTSAEREEG") == "SECRET MESSAGE" 46assert ( 47 decodeSimpleCipher("T SAENG SR MGARJ H U!SSTE TFECORIIEYSELUOOS") 48 == "THIS IS A LONGER SECRET MESSAGE JUST FOR YOU!" 49) 50print("Passed!")