mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-01-18 08:17:01 +00:00
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.
This commit is contained in:
parent
2383c289eb
commit
2faf238491
|
@ -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()
|
||||
|
|
Loading…
Reference in New Issue
Block a user