Encrypt a given `plaintext` (string) and `key` (string), returning the encrypted ciphertext. >>> encrypt("hello world", "coffee") 'jsqqs avvwo' >>> encrypt("coffee is good as python", "TheAlgorithms") 'vvjfpk wj ohvp su ddylsv' >>> encrypt("coffee is good as python", 2)
(plaintext: str, key: str)
| 10 | |
| 11 | |
| 12 | def encrypt(plaintext: str, key: str) -> str: |
| 13 | """ |
| 14 | Encrypt a given `plaintext` (string) and `key` (string), returning the |
| 15 | encrypted ciphertext. |
| 16 | |
| 17 | >>> encrypt("hello world", "coffee") |
| 18 | 'jsqqs avvwo' |
| 19 | >>> encrypt("coffee is good as python", "TheAlgorithms") |
| 20 | 'vvjfpk wj ohvp su ddylsv' |
| 21 | >>> encrypt("coffee is good as python", 2) |
| 22 | Traceback (most recent call last): |
| 23 | ... |
| 24 | TypeError: key must be a string |
| 25 | >>> encrypt("", "TheAlgorithms") |
| 26 | Traceback (most recent call last): |
| 27 | ... |
| 28 | ValueError: plaintext is empty |
| 29 | >>> encrypt("coffee is good as python", "") |
| 30 | Traceback (most recent call last): |
| 31 | ... |
| 32 | ValueError: key is empty |
| 33 | >>> encrypt(527.26, "TheAlgorithms") |
| 34 | Traceback (most recent call last): |
| 35 | ... |
| 36 | TypeError: plaintext must be a string |
| 37 | """ |
| 38 | if not isinstance(plaintext, str): |
| 39 | raise TypeError("plaintext must be a string") |
| 40 | if not isinstance(key, str): |
| 41 | raise TypeError("key must be a string") |
| 42 | |
| 43 | if not plaintext: |
| 44 | raise ValueError("plaintext is empty") |
| 45 | if not key: |
| 46 | raise ValueError("key is empty") |
| 47 | |
| 48 | key += plaintext |
| 49 | plaintext = plaintext.lower() |
| 50 | key = key.lower() |
| 51 | plaintext_iterator = 0 |
| 52 | key_iterator = 0 |
| 53 | ciphertext = "" |
| 54 | while plaintext_iterator < len(plaintext): |
| 55 | if ( |
| 56 | ord(plaintext[plaintext_iterator]) < 97 |
| 57 | or ord(plaintext[plaintext_iterator]) > 122 |
| 58 | ): |
| 59 | ciphertext += plaintext[plaintext_iterator] |
| 60 | plaintext_iterator += 1 |
| 61 | elif ord(key[key_iterator]) < 97 or ord(key[key_iterator]) > 122: |
| 62 | key_iterator += 1 |
| 63 | else: |
| 64 | ciphertext += chr( |
| 65 | ( |
| 66 | (ord(plaintext[plaintext_iterator]) - 97 + ord(key[key_iterator])) |
| 67 | - 97 |
| 68 | ) |
| 69 | % 26 |