I am trying write pythonic code to reverse the words in a sentence
ex:
input: "hello there friend"
output: "friend there hello"
code:
class Solution:
def swap(self, w):
return w[::-1]
def reverseWords(self, s):
w = self.swap(s).split()
return ' '.join(for x in w: swap(x))
I am having a bit of trouble getting this to work. I need help on the return statement
You're calling the swap/split in the wrong order. Use this instead:
w = self.swap(s.split())
Then your return shouldn't need to do any comprehension:
return ' '.join(w)
While there's not a whole lot wrong with wrapping it in a class, it's not exactly the most pythonic way to do things. Here's a shorter version of what you're trying to do:
def reverse(sentence):
return ' '.join(sentence.split()[::-1])
Output:
In [29]: reverse("hello there friend")
Out[29]: 'friend there hello'
Another one
def revereString(orgString):
result = []
splittedWords = orgString.split(" ")
for item in range(len(splittedWords)-1, -1, -1):
result.append(splittedWords[item])
return result
print(revereString('Hey ho hay'))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.