samedi 1 février 2020

Python recursive function doesn't return random choice

I am trying to get random work in python using random module. My function is as below:

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

When I import this function in ipython console and run as get_random_word(max_length=5), I get this result:

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

As you see from output, function calls itself until it finds the word with length less than 5. But at the end it returns very first random word. What is wrong with my function?




Aucun commentaire:

Enregistrer un commentaire