Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/354.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python递归函数没有';t返回随机选择_Python_Recursion_Random - Fatal编程技术网

Python递归函数没有';t返回随机选择

Python递归函数没有';t返回随机选择,python,recursion,random,Python,Recursion,Random,我试图使用random模块在python中获得随机工作。我的职能如下: import random word_file = "/usr/share/dict/words" WORDS = open(word_file).read().splitlines() def get_random_word(max_length=None): word = random.choice(WORDS) print(word) if not max_length:

我试图使用
random
模块在python中获得随机工作。我的职能如下:

import random

word_file = "/usr/share/dict/words"
WORDS = open(word_file).read().splitlines()


def get_random_word(max_length=None):
    word = random.choice(WORDS)
    print(word)

    if not max_length:
        return word

    if len(word) > max_length:
        get_random_word(max_length)

    return word
当我在
ipython
控制台中导入此函数并作为
get\u random\u word(max\u length=5)
运行时,我得到以下结果:

Latasha's
Hammond's
evacuated
aviary
misconducted
airfare's
controllable
unduly
gaunt
Out[32]: "Latasha's"

正如您从输出中看到的,函数会调用自身,直到找到长度小于5的单词。但最后它返回第一个随机单词。我的函数有什么问题?

您没有在函数中指定返回值

        get_random_word(max_length)

    return word
应该是:

    if len(word) > max_length:
        word = get_random_word(max_length)

    return word

在if语句中,需要返回值

if len(word) > max_length:
        return get_random_word(max_length)

最后一个
返回字
将返回内存中的最后一个字,在这种情况下,这是第一个递归情况,因为您从不从基本情况返回。这是一个简单的递归错误。变量字的值不会通过递归调用保留。您必须指定返回值

word = get_random_word(max_length)

我认为您的代码可以工作,您根本不需要这一行
返回单词
,也不需要调用
get\u random\u word
内部打印(如果需要)。

Python中的递归效率很低,因为重复调用用户定义的函数,而且有限,如果不尽快终止递归,最终会导致堆栈溢出。因此,虽然对问题的修复是微不足道的(返回递归调用的返回值),但这是一个没有实际意义的问题,因为递归是错误的开始方法

相反,使用
while
循环调用
random.choice
,直到得到符合您条件的单词

import random

word_file = "/usr/share/dict/words"
WORDS = open(word_file).read().splitlines()


def get_random_word(max_length=None):
    while True:
        word = random.choice(WORDS)
        if max_length is None or len(word) <= max_length:
            return word
随机导入
word_file=“/usr/share/dict/words”
WORDS=open(word_文件).read().splitlines()
def get_random_字(最大长度=无):
尽管如此:
单词=随机。选择(单词)

如果max_length为None或len(word),则不要对此使用递归。使用
while
循环。@切普纳:你能解释一下为什么吗?(请写下你推荐的方式作为答案)