From 2faf238491d9b8020cbd7937add9bdfbe9347de1 Mon Sep 17 00:00:00 2001 From: Riddhima Deshmukh <115169787+ridds-io@users.noreply.github.com> Date: Mon, 28 Oct 2024 09:52:48 +0530 Subject: [PATCH] Update rot13.py Using List for Accumulation: Instead of string concatenation within the loop, result.append() is used to create a list, and join is called at the end to concatenate the list into a string. This is more efficient for larger strings. Removed Unnecessary Parameter n: Eliminating the n parameter makes the function simpler and ensures consistent ROT13 encryption/decryption. Refactored Doctest and Assertions: The doctest examples are consistent with the revised function, ensuring reversibility through dencrypt(dencrypt(s)) == s without additional parameters. --- ciphers/rot13.py | 29 ++++++++++++++--------------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/ciphers/rot13.py b/ciphers/rot13.py index b367c3215..fb424d186 100644 --- a/ciphers/rot13.py +++ b/ciphers/rot13.py @@ -1,37 +1,36 @@ -def dencrypt(s: str, n: int = 13) -> str: +def dencrypt(s: str) -> str: """ - https://en.wikipedia.org/wiki/ROT13 - + Applies ROT13 encryption or decryption to the input string. + + Example usage: >>> msg = "My secret bank account number is 173-52946 so don't tell anyone!!" - >>> s = dencrypt(msg) - >>> s + >>> encrypted = dencrypt(msg) + >>> encrypted "Zl frperg onax nppbhag ahzore vf 173-52946 fb qba'g gryy nalbar!!" - >>> dencrypt(s) == msg + >>> dencrypt(encrypted) == msg True """ - out = "" + result = [] for c in s: if "A" <= c <= "Z": - out += chr(ord("A") + (ord(c) - ord("A") + n) % 26) + result.append(chr(ord("A") + (ord(c) - ord("A") + 13) % 26)) elif "a" <= c <= "z": - out += chr(ord("a") + (ord(c) - ord("a") + n) % 26) + result.append(chr(ord("a") + (ord(c) - ord("a") + 13) % 26)) else: - out += c - return out - + result.append(c) + return "".join(result) def main() -> None: s0 = input("Enter message: ") - s1 = dencrypt(s0, 13) + s1 = dencrypt(s0) print("Encryption:", s1) - s2 = dencrypt(s1, 13) + s2 = dencrypt(s1) print("Decryption: ", s2) if __name__ == "__main__": import doctest - doctest.testmod() main()