Decrypt a given `ciphertext` (string) and `key` (string), returning the decrypted ciphertext. >>> decrypt("jsqqs avvwo", "coffee") 'hello world' >>> decrypt("vvjfpk wj ohvp su ddylsv", "TheAlgorithms") 'coffee is good as python' >>> decrypt("vvjfpk wj ohvp su ddylsv", "
(ciphertext: str, key: str)
| 75 | |
| 76 | |
| 77 | def decrypt(ciphertext: str, key: str) -> str: |
| 78 | """ |
| 79 | Decrypt a given `ciphertext` (string) and `key` (string), returning the decrypted |
| 80 | ciphertext. |
| 81 | |
| 82 | >>> decrypt("jsqqs avvwo", "coffee") |
| 83 | 'hello world' |
| 84 | >>> decrypt("vvjfpk wj ohvp su ddylsv", "TheAlgorithms") |
| 85 | 'coffee is good as python' |
| 86 | >>> decrypt("vvjfpk wj ohvp su ddylsv", "") |
| 87 | Traceback (most recent call last): |
| 88 | ... |
| 89 | ValueError: key is empty |
| 90 | >>> decrypt(527.26, "TheAlgorithms") |
| 91 | Traceback (most recent call last): |
| 92 | ... |
| 93 | TypeError: ciphertext must be a string |
| 94 | >>> decrypt("", "TheAlgorithms") |
| 95 | Traceback (most recent call last): |
| 96 | ... |
| 97 | ValueError: ciphertext is empty |
| 98 | >>> decrypt("vvjfpk wj ohvp su ddylsv", 2) |
| 99 | Traceback (most recent call last): |
| 100 | ... |
| 101 | TypeError: key must be a string |
| 102 | """ |
| 103 | if not isinstance(ciphertext, str): |
| 104 | raise TypeError("ciphertext must be a string") |
| 105 | if not isinstance(key, str): |
| 106 | raise TypeError("key must be a string") |
| 107 | |
| 108 | if not ciphertext: |
| 109 | raise ValueError("ciphertext is empty") |
| 110 | if not key: |
| 111 | raise ValueError("key is empty") |
| 112 | |
| 113 | key = key.lower() |
| 114 | ciphertext_iterator = 0 |
| 115 | key_iterator = 0 |
| 116 | plaintext = "" |
| 117 | while ciphertext_iterator < len(ciphertext): |
| 118 | if ( |
| 119 | ord(ciphertext[ciphertext_iterator]) < 97 |
| 120 | or ord(ciphertext[ciphertext_iterator]) > 122 |
| 121 | ): |
| 122 | plaintext += ciphertext[ciphertext_iterator] |
| 123 | else: |
| 124 | plaintext += chr( |
| 125 | (ord(ciphertext[ciphertext_iterator]) - ord(key[key_iterator])) % 26 |
| 126 | + 97 |
| 127 | ) |
| 128 | key += chr( |
| 129 | (ord(ciphertext[ciphertext_iterator]) - ord(key[key_iterator])) % 26 |
| 130 | + 97 |
| 131 | ) |
| 132 | key_iterator += 1 |
| 133 | ciphertext_iterator += 1 |
| 134 | return plaintext |