Skip to content

Instantly share code, notes, and snippets.

@bcowell
Created October 23, 2019 16:09
Show Gist options
  • Save bcowell/a4b8e51b68ead2c89cda073ecddf940f to your computer and use it in GitHub Desktop.
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
# 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