Write a function that takes in a string of one or more words, and returns the same string, but with all words that have five or more letters reversed (Just like the name of this Kata). Strings passed in will consist of only letters and spaces. Spaces will be included only when more than one word is present.
Examples:
"Hey fellow warriors" --> "Hey wollef sroirraw"
"This is a test --> "This is a test"
"This is another test" --> "This is rehtona test"
Resolution:
def spin_words(sentence):
# Split the sentence into words
words = sentence.split()
# Process each word
result = []
for word in words:
# If word length is 5 or more, reverse it, otherwise keep it as is
if len(word) >= 5:
result.append(word[::-1])
else:
result.append(word)
# Join words back with spaces
return " ".join(result)
# Test cases
test_cases = [
"Hey fellow warriors",
"This is a test",
"This is another test",
"Welcome",
"Just kidding around"
]
# Run tests
for test in test_cases:
print(f'"{test}" --> "{spin_words(test)}"')
How it works:
- sentence.split() splits the input string into a list of words (by default splits on whitespace)
- Iterates through each word:
- Checks length with len(word)
- If 5 or more letters, reverses it using string slicing word[::-1]
- If less than 5 letters, keeps it unchanged
- Joins the processed words back together with spaces using ” “.join()
- Returns the final string
Output:
"Hey fellow warriors" --> "Hey wollef sroirraw" "This is a test" --> "This is a test" "This is another test" --> "This is rehtona test" "Welcome" --> "emocleW" "Just kidding around" --> "Just gniddik dnuora"
Alternative one-liner :
def spin_words(sentence):
return " ".join(word[::-1] if len(word) >= 5 else word for word in sentence.split())