Simple Encryption - Alternating Split π₯
- Implement a pseudo-encryption algorithm which given a string S and an integer N
- Concatenates all the odd-indexed characters of S with all the even-indexed characters of S.
- This process should be repeated N times.
Examples:
encrypt("012345", 1) => "135024"
encrypt("012345", 2) => "135024" -> "304152"
encrypt("012345", 3) => "135024" -> "304152" -> "012345"
- Together with the encryption function, you should also implement A decryption function which reverses the process.
- If the string S is an empty value or the integer N is not positive, return the first argument without changes.
Task URL: Link
My Solution:
def encrypt(text: str, n: int) -> str:
if not text or n < 0:
return text
for _ in range(n):
odd_chars = []
even_chars = []
for i, char in enumerate(text):
if i % 2:
odd_chars.append(char)
else:
even_chars.append(char)
text = ''.join(odd_chars + even_chars)
return text
def decrypt(encrypted_text: str, n: int) -> str:
if not encrypted_text or n < 0:
return encrypted_text
length = len(encrypted_text)
half_length = length // 2
for _ in range(n):
odd_chars = encrypted_text[:half_length]
even_chars = encrypted_text[half_length:]
decrypted_chars = []
for i, j in zip(even_chars, odd_chars):
decrypted_chars.append(i)
decrypted_chars.append(j)
if length % 2 == 1:
decrypted_chars.append(even_chars[-1])
encrypted_text = ''.join(decrypted_chars)
return encrypted_text
Code Snapshot:
Learn Python
Python top free courses from Courseraππ―π
π₯
Top comments (0)