-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverse_words.py
More file actions
48 lines (41 loc) · 1.13 KB
/
reverse_words.py
File metadata and controls
48 lines (41 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
'''
7 kyu
Reverse words
https://www.codewars.com/kata/5259b20d6021e9e14c0010d4
'''
# ---- SOLUTION ----
def reverse_words(text):
result = ''
while text != '':
lblank = len(text) - len(text.lstrip())
if lblank > 0:
result += text[:lblank]
text = text.lstrip()
lword = text.find(' ')
if lword == -1:
lword = len(text)
word = text[:lword]
result += word[lword::-1]
text = text[lword::]
return result
# ---- SECOND SOLUTION ----
'''
def reverse_words(text):
return ' '.join(word[::-1] for word in text.split(' '))
'''
# ---- TEST ----
def dotest(text, expected):
actual = reverse_words(text)
status = 'OK' if expected == actual else 'FAIL'
print(f'Text = "{text}", expected = "{expected}", actual = "{actual}" -> {status}')
def main():
dotest('The quick brown fox jumps over the lazy dog.', 'ehT kciuq nworb xof spmuj revo eht yzal .god')
dotest('apple', 'elppa')
dotest('a b c d', 'a b c d')
dotest(' double spaced words ', ' elbuod decaps sdrow ')
dotest(' ', ' ')
dotest(' du', ' ud')
dotest('du ', 'ud ')
dotest('', '')
if __name__ == "__main__":
main()