mirror of
https://github.com/TheAlgorithms/Python.git
synced 2026-09-28 21:45:27 +08:00
* fix: raise ValueError in encode() for non-lowercase input encode() previously accepted uppercase letters, digits, and other non-lowercase characters silently, producing incorrect/out-of-range values (e.g. negative numbers for uppercase letters) instead of failing. Add input validation using str.islower() and str.isalpha() to raise a ValueError when the input isn't purely lowercase a-z. Added a doctest covering the new error case. * resolved doctest * Fix Ruff 0.16 lint failures * Enhance encode function error handling examples Update error handling in encode function to include examples for mixed case and invalid characters. * Fix indentation in test_cancer_data function * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: Christian Clauss <cclauss@me.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
50 lines
1.3 KiB
Python
50 lines
1.3 KiB
Python
"""
|
|
Convert a string of characters to a sequence of numbers
|
|
corresponding to the character's position in the alphabet.
|
|
|
|
https://www.dcode.fr/letter-number-cipher
|
|
http://bestcodes.weebly.com/a1z26.html
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
def encode(plain: str) -> list[int]:
|
|
"""
|
|
>>> encode("myname")
|
|
[13, 25, 14, 1, 13, 5]
|
|
>>> encode("abCd")
|
|
Traceback (most recent call last):
|
|
...
|
|
ValueError: plain must contain only lowercase letters (a-z)
|
|
>>> encode("n0w")
|
|
Traceback (most recent call last):
|
|
...
|
|
ValueError: plain must contain only lowercase letters (a-z)
|
|
>>> encode("later!")
|
|
Traceback (most recent call last):
|
|
...
|
|
ValueError: plain must contain only lowercase letters (a-z)
|
|
"""
|
|
if not plain.islower() or not plain.isalpha():
|
|
raise ValueError("plain must contain only lowercase letters (a-z)")
|
|
return [ord(elem) - 96 for elem in plain]
|
|
|
|
|
|
def decode(encoded: list[int]) -> str:
|
|
"""
|
|
>>> decode([13, 25, 14, 1, 13, 5])
|
|
'myname'
|
|
"""
|
|
return "".join(chr(elem + 96) for elem in encoded)
|
|
|
|
|
|
def main() -> None:
|
|
encoded = encode(input("-> ").strip().lower())
|
|
print("Encoded: ", encoded)
|
|
print("Decoded:", decode(encoded))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|