Skip to content

Instantly share code, notes, and snippets.

@beala
Created April 7, 2012 18:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save beala/2331327 to your computer and use it in GitHub Desktop.
Save beala/2331327 to your computer and use it in GitHub Desktop.
Reverse Word Order
def rev_words(s):
'''Returns the string `s` with its words in the reverse order.
Example: rev_words("Reverse this!") #"this! Reverse"
'''
def helper(s, word_acc, str_acc):
# Base case: Return `word_acc` plus whatever words
# you have in the string acc.
if len(s) == 0:
return word_acc + str_acc
# This is the end of a word. Clear `word_acc`, and start with
# the next word.
elif s[0] == " ":
return helper(s[1:], "", " " + word_acc + str_acc)
# In the middle of a word. Add the letter to `word_acc`, and continue
else:
return helper(s[1:], word_acc + s[0], str_acc)
return helper(s, "", "")
if __name__=="__main__":
assert rev_words("") == ""
assert rev_words(" ") == " "
assert rev_words("a") == "a"
assert rev_words("Captain Kirk") == "Kirk Captain"
assert rev_words(" Captain Kirk ") == " Kirk Captain "
assert rev_words("THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG") == "DOG LAZY THE OVER JUMPS FOX BROWN QUICK THE"
assert rev_words("Reverse this string.") == "string. this Reverse"
assert rev_words(" many spaces many spaces") == "spaces many spaces many "
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment