mirror of
https://github.com/TheAlgorithms/Python.git
synced 2026-03-13 09:50:19 +08:00
* docs: refine docstring and simplify reverse_letters implementation Updated the docstring for clarity and improved the logic for reversing words. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update reverse_letters.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>
25 lines
733 B
Python
25 lines
733 B
Python
def reverse_letters(sentence: str, length: int = 0) -> str:
|
|
"""
|
|
Reverse all words that are longer than the given length of characters in a sentence.
|
|
If ``length`` is not specified, it defaults to 0.
|
|
|
|
>>> reverse_letters("Hey wollef sroirraw", 3)
|
|
'Hey fellow warriors'
|
|
>>> reverse_letters("nohtyP is nohtyP", 2)
|
|
'Python is Python'
|
|
>>> reverse_letters("1 12 123 1234 54321 654321", 0)
|
|
'1 21 321 4321 12345 123456'
|
|
>>> reverse_letters("racecar")
|
|
'racecar'
|
|
"""
|
|
return " ".join(
|
|
word[::-1] if len(word) > length else word for word in sentence.split()
|
|
)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
import doctest
|
|
|
|
doctest.testmod()
|
|
print(reverse_letters("Hey wollef sroirraw"))
|