逻辑错误(Pythons):没有写入输出但函数有效吗?(Logic Error (Pythons): Not getting write output but function works?)

编程入门 行业动态 更新时间:2024-10-25 04:19:08
逻辑错误(Pythons):没有写入输出但函数有效吗?(Logic Error (Pythons): Not getting write output but function works?)

输入:

Akash Das

预期收益:

Das Akash

我的代码正在输出:

Da Akash

这是我的代码:

#a def firstWord(string): space = string.find(" ") first = string[:space] return first #b def removeFirst(string): space = string.find(" ") word = string[space + 1:] return word print(removeFirst("Akash Das")) #c def reversePhrase(string): reverse = [] numSpace = string.count(" ") reverse.append(firstWord(string)) while numSpace > 0: string = removeFirst(string) reverse.insert(0, firstWord(string)) numSpace -= 1 return reverse def printReverse(string): for i in reversePhrase(string): print (i, end = " ") #d def main(): string = input("Enter a phrase. ") print("Your reversed phrase is", end = " ") #call reverse printReverse(string) main()

这是输出:

>>> Das Enter a phrase. Akash Das Your reversed phrase is Da Akash >>>

Inputted:

Akash Das

Expected return:

Das Akash

My code is outputting:

Da Akash

Here's my code:

#a def firstWord(string): space = string.find(" ") first = string[:space] return first #b def removeFirst(string): space = string.find(" ") word = string[space + 1:] return word print(removeFirst("Akash Das")) #c def reversePhrase(string): reverse = [] numSpace = string.count(" ") reverse.append(firstWord(string)) while numSpace > 0: string = removeFirst(string) reverse.insert(0, firstWord(string)) numSpace -= 1 return reverse def printReverse(string): for i in reversePhrase(string): print (i, end = " ") #d def main(): string = input("Enter a phrase. ") print("Your reversed phrase is", end = " ") #call reverse printReverse(string) main()

And here's the output:

>>> Das Enter a phrase. Akash Das Your reversed phrase is Da Akash >>>

最满意答案

CSZ是对的,这更简单。 但你的问题是在firstWord 。 如果字符串没有空格,则find将返回-1。 所以space将为-1, string[:space]将为string[:-1] ,这是除最后一个字符之外的所有字符。 您只需要检查是否确实找到了空格:

def firstWord(string): space = string.find(" ") first = string[:space] if space >= 0 else string return first

CSZ is right, that is simpler. But your problem is in firstWord. If the string has no spaces, then find will return -1. So space will be -1, and string[:space] will be string[:-1] which is all characters except the last. You just need to check whether you actually found a space:

def firstWord(string): space = string.find(" ") first = string[:space] if space >= 0 else string return first

更多推荐

本文发布于:2023-04-29 06:01:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1335249.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   逻辑   错误   Pythons   Logic

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!