gpt4 book ai didi

python - 具有相同参数的递归函数

转载 作者:行者123 更新时间:2023-11-30 23:11:09 25 4
gpt4 key购买 nike

我正在用 python 创建一个基于文本的游戏,但遇到了障碍。我有一个函数可以检查用户输入是否包含某些单词,如果包含,则返回用户输入,否则它将重新要求输入。如果您编写的内容不包含其中一个单词,它将重新调用该函数。

def contains_words(prompt, words):

user_input = raw_input(prompt).strip().lower()


if user_input == "instructions":
print
instructions()
print
contains_words(prompt, words)

elif user_input == "i" or user_input == "inventory":
if len(inventory) == 0:
print
print "There is nothing in your inventory."
print
contains_words(prompt, words)
else:
print "Your inventory contains: " + inventory
contains_words(prompt, words)

else:
if user_input in words:
return user_input
else:
print
print "I did not understand your answer, consider rephrasing."
contains_words(prompt , words)

我这样调用它:

pizza = contains_words("Do you like pizza?", ["yes", "no"])

在此功能中,您可以调出说明或库存,然后它会调用该功能。如果您在第一次被问到时在答案中添加了其中一个单词,则一切都会正常进行。当您输入不正确的内容、调出库存或调出说明时,就会出现问题。它导致函数不返回任何内容,而不返回用户输入。为什么会发生这种情况?是不是因为函数重置所以参数等于none?

最佳答案

让我们看一下该函数的调用示例。

pizza = contains_words("Do you like pizza?", ["yes", "no"])

假设用户输入指令。您的第一个 if 语句是 True,因此我们进入该 block ,调用 instructions() (大概将指令打印到控制台),并且 contains_words 再次被调用。假设用户这次输入yes。我们将讨论最后一个 if 语句,它将是 True,并且对 contains_words 的调用将返回 yes -- 调用它的地方

所以,现在我们将堆栈备份到 contains_words 的原始调用。返回值被忽略,因为该函数是在一行上单独调用的,而不是作为另一个函数或语句的参数。现在我们已经完成了这个 if block ,函数中的下一步就是......什么也没有。其余的 ifelifelse 没有任何意义(因为原始 if 的计算结果为 True),我们退出函数的底部。它什么也不返回(实际上是None)。 (检查披萨的类型即可看到。)

解决方案是将递归调用更改为return contains_words(prompt, Words),这样当函数退出每个递归调用时,它会将返回值传递到堆栈中,或者,因为这样无论如何只是尾递归,用循环替换它:

def contains_words(prompt, words):

while True:
user_input = raw_input(prompt).strip().lower()


if user_input == "instructions":
print
instructions()
print


elif user_input == "i" or user_input == "inventory":
if len(inventory) == 0:
print
print "There is nothing in your inventory."
print
else:
print "Your inventory contains: " + inventory

else:
if user_input in words:
return user_input
else:
print
print "I did not understand your answer, consider rephrasing."

这将避免涉及潜在多次递归的内存问题。

关于python - 具有相同参数的递归函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30289891/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com