我有这段代码:
text = str(input('Input sentence, please: '))
def reverse(text):
r_text = ''
index = len(text) - 1
while index >= 0:
r_text += text[index]
index -= 1
return r_text
print(reverse(text))
但输出是例如:Whats up - > pu stahW我需要它 - > up Whats
换句话说:
编写用于反转句子中单词的函数的伪代码和代码。
输入:
"This is awesome"
输出:
"awesome is This".
给出大O符号。
答案 0 :(得分:4)
def reverse_order(sentence):
return ' '.join(sentence.split(' ')[::-1])
答案 1 :(得分:1)
split
应该有效。用空格把它块起来。然后反转阵列。最后加入反转阵列' '
a = "What's up"
bits = a.split()
print(bits) # yields: ["What's", 'up']
bits_reversed = bits[::-1]
print(bits_reversed) # yields: ['up', "What's"]
print(' '.join(bits_reversed))
答案 2 :(得分:0)
你可以这样做:
>>> " ".join("Hello world".split()[::-1])
'world Hello'
或者,如果你想在一个函数中使用它:
>>> def reverse(text):
... return " ".join(text.split()[::-1])
...
>>> reverse("Hello world")
'world Hello'
答案 3 :(得分:0)
您可以对reverse()
使用list
功能:
s = "What's up"
l1 = s.split()
l1.reverse()
res = ' '.join(l1)
<强>输出:强>
>>> res
"up What's"
在自定义功能中:
def reverse_sentence(s):
l = s.split()
l.reverse()
return ' '.join(l)
<强>输出:强>
>>> reverse_sentence("What's up")
"up What's"