首页 > 解决方案 > 将单词反转到位

问题描述

前任。输入:rat the ate cat the

输出:the cat ate the rat

到目前为止,这是我的代码:

def reverse_message(starting, ending, msg):

    while(starting < ending):
        msg[starting], msg[ending] = msg[ending], msg[starting]
        starting += 1 
        ending -= 1

def reverse_words(msg):

    # Decode the message by reversing the words
    # reverse entire message
    reverse_message(0, len(msg) - 1, msg)

    #reverse each word
    starting = 0
    for i in range(len(msg)):
        if ((msg[i] == ' ') or (i == len(msg) - 1)):
            reverse_message(starting, i-1, msg)
            starting = i+1

我究竟做错了什么?任何帮助将不胜感激。

标签: pythonpython-3.x

解决方案


这可以在一行中完成: str=' '.join(list(input().split(' '))[::-1])


推荐阅读