python - 将单词反转到位
问题描述
前任。输入: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
我究竟做错了什么?任何帮助将不胜感激。
解决方案
这可以在一行中完成:
str=' '.join(list(input().split(' '))[::-1])
推荐阅读
- flutter - Dart - 如何将函数作为参数传递
- sql - 如果存在更新,则查询从表中获取更新的记录,否则获取新记录
- php - 如何在 mysql 中建立数据库关系并使用 eloquent 和 join
- java - Maven 强制依赖项使用 Spring Boot 低版本
- javascript - 为什么我的文本输入字段被锁定以进行编辑?
- android - 迁移到 Androidx 后出错。“android.support.constraint.R.styleable.ImageFilterView”转换为“android.constraintlayout.R”
- postgresql - 当子选择很快时,了解为什么“从不存在中删除”会变慢
- firebase - 如何从颤动的firestore文档字段中获取数据?
- jazzy - 编辑 Jazzy HTML 生成以添加自定义链接
- ios - 在 ios swift 中的 NotificationService 中播放流式 URL