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?
Recursion in Python is inefficient, due to repeated calls to user-defined functions, and limited, in that you will eventually overflow the stack if you don't terminate the recursion soon enough. As such, while the fix to your problem is trivial (return the return value of the recursive call), it's a moot point because recursion is the wrong approach to begin with.
Instead, use a while
loop to call random.choice
until you get a word that fits your condition.
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
Thanks for your help.