The challenge
Write a function that reverses the words in a given string. A word can also fit an empty string. If this is not clear enough, here are some examples:
As the input may have trailing spaces, you will also need to ignore unnecessary whitespace.
Example (Input –> Output)
1
2
|
"Hello World" --> "World Hello"
"Hi There." --> "There. Hi"
|
The solution in Python code
Option 1:
1
2
3
4
|
import re
def reverse(st):
return " ".join(re.sub('\s+', ' ', st).strip().split(" ")[::-1])
|
Option 2:
1
2
|
def reverse(st):
return " ".join(reversed(st.split())).strip()
|
Option 3:
1
2
3
|
def reverse(st):
s = st.split()
return ' '.join(s[::-1])
|
Option 4:
1
2
3
4
|
def reverse(st):
st = st.split()
st.reverse()
return ' '.join(st)
|
Test cases to validate our solution
1
2
3
4
5
6
7
8
9
|
import test
from solution import reverse
@test.describe("Fixed Tests")
def fixed_tests():
@test.it('Basic Test Cases')
def basic_test_cases():
test.assert_equals(reverse('Hello World'), 'World Hello')
test.assert_equals(reverse('Hi There.'), 'There. Hi')
|