简体   繁体   中英

RecursionError when calling a function multiple times

I have a function which is supposed to get a word and choose one of its letters by random. I also have a list of already chosen letters. If the chosen letter already exists in this list, I use recursion to choose another letter:

def choose(word, chosen_list):
    chosen_letter = random.choice(word)
    if chosen_letter not in chosen_list:
        print("Found")
    else:
        choose(word, chosen_list)

The problem is that when choose function is called multiple times, I encounter an error:

chosen_letter = random.choice(word)
  File "...\random.py", line 259, in choice
    i = self._randbelow(len(seq))
  File "...\random.py", line 232, in _randbelow
    if type(random) is BuiltinMethod or type(getrandbits) is Method:
RecursionError: maximum recursion depth exceeded while calling a Python object

Why this is happening?

In python recursion is limited (to around 1000 calls I think). This is done to avoid infinite calls. You can overcome this by increasing the recursion limit using the sys module. Try:

import sys

sys.setrecursionlimit(some_numerical_limit)

For more information, you can visit this geeksforgeeks article

Consider the case where all the letters are in the chosen list.Also if the selected letter is already in the chosen list you should remove it. Here is an example

    import random
    def choose(word, chosen_list):
        if len(word)>0:
          chosen_letter = random.choice(word)
          if chosen_letter not in chosen_list:
             print("Found")
          else:
             choose(word.replace(chosen_letter,""), chosen_list)
        else:
          print("end")

Here we are removing the letter that is already in the list. If no such letter exists the program will print end

Don't use recursion, this is not appropriate here.


Use a while loop, to pick a letter until it's not in the given list (give it a clearer name)

def choose(word, exclude_list):
    chosen_letter = random.choice(word)
    while chosen_letter in exclude_list:
        chosen_letter  = random.choice(word)
    print("Found a letter that is not in list", chosen_letter)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM