Created
October 23, 2019 16:09
-
-
Save bcowell/a4b8e51b68ead2c89cda073ecddf940f to your computer and use it in GitHub Desktop.
Given a string sentence, return the sentence with the words in the reverse 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
# Given a string sentence, return the sentence with the words in the reverse order | |
# "I like apples" => "apples like I" | |
def reverseSentence(sentence): | |
words = sentence.split(" ") | |
return " ".join(words[::-1]) | |
# If input is an array of characters instead of a string | |
# ['I', ' ', 'l' , 'i', 'k', e', ' ', 'a', 'p', 'p', 'l', 'e', 's'] | |
# => ['a', 'p', 'p', 'l', 'e', 's', ' ', 'l', 'i', 'k', 'e', ' ', 'I'] | |
def reverseSentenceArray(arr): | |
str = "".join(arr) # convert list to string | |
return list(reverseWords(str)) | |
sentence = "I like apples" | |
print(reverseSentence(sentence)) | |
print(reverseSentenceArray(list(sentence))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment