逻辑错误(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 DasExpected return:
Das AkashMy code is outputting:
Da AkashHere'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 firstCSZ 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更多推荐
发布评论