Advertisement
alex0sunny

reverse words

Sep 5th, 2022
1,002
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.47 KB | None | 0 0
  1. def reverse_words(s):
  2.     s.reverse()
  3.     start = 0
  4.     for end in range(len(s)):
  5.         if end == len(s)-1 or s[end+1] == ' ':
  6.             for shift in range((end+1-start) // 2):
  7.                 s[start+shift], s[end-shift] = s[end-shift], s[start+shift]
  8.             start = end + 2
  9.  
  10.  
  11. s = list('abc f')
  12. reverse_words(s)
  13. assert s == list('f abc')
  14.  
  15. s = list('x bla')
  16. reverse_words(s)
  17. assert s == list('bla x')
  18.  
  19. s = list('')
  20. reverse_words(s)
  21. assert s == list('')
  22.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement