Created
April 7, 2012 18:47
-
-
Save beala/2331327 to your computer and use it in GitHub Desktop.
Reverse Word Order
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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