mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-01-30 22:23:42 +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!!"
|
>>> msg = "My secret bank account number is 173-52946 so don't tell anyone!!"
|
||||||
>>> s = dencrypt(msg)
|
>>> encrypted = dencrypt(msg)
|
||||||
>>> s
|
>>> encrypted
|
||||||
"Zl frperg onax nppbhag ahzore vf 173-52946 fb qba'g gryy nalbar!!"
|
"Zl frperg onax nppbhag ahzore vf 173-52946 fb qba'g gryy nalbar!!"
|
||||||
>>> dencrypt(s) == msg
|
>>> dencrypt(encrypted) == msg
|
||||||
True
|
True
|
||||||
"""
|
"""
|
||||||
out = ""
|
result = []
|
||||||
for c in s:
|
for c in s:
|
||||||
if "A" <= c <= "Z":
|
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":
|
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:
|
else:
|
||||||
out += c
|
result.append(c)
|
||||||
return out
|
return "".join(result)
|
||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
s0 = input("Enter message: ")
|
s0 = input("Enter message: ")
|
||||||
|
|
||||||
s1 = dencrypt(s0, 13)
|
s1 = dencrypt(s0)
|
||||||
print("Encryption:", s1)
|
print("Encryption:", s1)
|
||||||
|
|
||||||
s2 = dencrypt(s1, 13)
|
s2 = dencrypt(s1)
|
||||||
print("Decryption: ", s2)
|
print("Decryption: ", s2)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
import doctest
|
import doctest
|
||||||
|
|
||||||
doctest.testmod()
|
doctest.testmod()
|
||||||
main()
|
main()
|
||||||
|
|
Loading…
Reference in New Issue
Block a user