温馨提示:本文翻译自stackoverflow.com,查看原文请点击:recursion - Python recursive function doesn't return random choice
python random recursion

recursion - Python递归函数不会返回随机选择

发布于 2020-04-10 11:45:08

我正在尝试使用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_random_word(max_length=5),得到以下结果:

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

从输出中可以看到,函数会自行调用,直到找到长度小于5的单词。但是最后,它返回第一个随机单词。我的功能出了什么问题?

查看更多

提问者
nicat9507
被浏览
43
chepner 2020-02-01 23:23

由于重复调用用户定义的函数,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