Simplify Capitalize Function (#12879)

* Simplify the capitalize function using ASCII arithmetic to make the algorithm five times faster.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Update capitalize.py

* Update capitalize.py

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Maxim Smolskiy <mithridatus@mail.ru>
This commit is contained in:
Milad Khoshdel
2025-08-24 13:37:39 +03:30
committed by GitHub
parent e224532107
commit a8c5616857

View File

@@ -1,6 +1,3 @@
from string import ascii_lowercase, ascii_uppercase
def capitalize(sentence: str) -> str:
"""
Capitalizes the first letter of a sentence or word.
@@ -19,11 +16,9 @@ def capitalize(sentence: str) -> str:
if not sentence:
return ""
# Create a dictionary that maps lowercase letters to uppercase letters
# Capitalize the first character if it's a lowercase letter
# Concatenate the capitalized character with the rest of the string
lower_to_upper = dict(zip(ascii_lowercase, ascii_uppercase))
return lower_to_upper.get(sentence[0], sentence[0]) + sentence[1:]
return sentence[0].upper() + sentence[1:]
if __name__ == "__main__":