File tree Expand file tree Collapse file tree 1 file changed +24
-5
lines changed
Expand file tree Collapse file tree 1 file changed +24
-5
lines changed Original file line number Diff line number Diff line change 11def reverse_letters (sentence : str , length : int = 0 ) -> str :
22 """
3- Reverse all words that are longer than the given length of characters in a sentence.
4- If ``length`` is not specified, it defaults to 0.
3+ Reverse words in a sentence that are longer than a specified length.
54
5+ Parameters:
6+ sentence (str): The input sentence containing words
7+ length (int): Minimum length of words to be reversed (default is 0)
8+
9+ Returns:
10+ str: Sentence with selected words reversed
11+
12+ Examples:
613 >>> reverse_letters("Hey wollef sroirraw", 3)
714 'Hey fellow warriors'
815 >>> reverse_letters("nohtyP is nohtyP", 2)
@@ -12,13 +19,25 @@ def reverse_letters(sentence: str, length: int = 0) -> str:
1219 >>> reverse_letters("racecar")
1320 'racecar'
1421 """
15- return " " .join (
16- word [::- 1 ] if len (word ) > length else word for word in sentence .split ()
17- )
22+
23+ # Split the sentence into individual words
24+ words = sentence .split ()
25+
26+ # Reverse words that have length greater than the specified value
27+ result = [
28+ word [::- 1 ] if len (word ) > length else word # reverse using slicing
29+ for word in words
30+ ]
31+
32+ # Join the processed words back into a sentence
33+ return " " .join (result )
1834
1935
2036if __name__ == "__main__" :
2137 import doctest
2238
39+ # Run test cases defined in docstring
2340 doctest .testmod ()
41+
42+ # Example execution
2443 print (reverse_letters ("Hey wollef sroirraw" ))
You can’t perform that action at this time.
0 commit comments