反转单词

时间:2019-04-21 05:06:03

标签: python python-3.x

例如输入: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

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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

首先,我将避免显式传递起始索引和结束索引,而是依赖消息本身,其中起始索引是字符串的第一个索引,而终止索引是字符串的最后一个索引,我也将传递字符串作为列表,因为字符串是可变的并且不能更改,但是列表可以。

def reverse_word(msg):

    starting = 0
    ending = len(msg)-1
    while(starting < ending):
        tmp = msg[starting]
        msg[starting] = msg[ending]
        msg[ending] = tmp
        starting += 1 
        ending -= 1

    return msg

此后,要反转字符串,我将首先反转整个字符串,然后将字符串中的每个单词反转到位,然后将字符串缝合在一起以输出。

def reverse_message(msg):

    #Convert the string into list of characters
    chars = list(msg)
    #Reverse entire list
    chars = reverse_word(chars)
    starting = 0
    i = 0
    result = []
    #Iterate through the reversed list, and pick individual words based on 
    #whitespace, and then reverse them in place
    while i < len(chars):
        if chars[i] == ' ':
            #Append all reversed words to another list
            result += reverse_word(chars[starting:i]) + [' ']
            starting = i+1
        i+=1
    #Reverse the last remaining word
    result += reverse_word(chars[starting:i])
    #Stitch the list back to string and return it
    return ''.join(result)

结果输出看起来像

print(reverse_message('rat the ate cat the'))
#the cat ate the rat