Home > front end >  Recursion leads to list IndexError
Recursion leads to list IndexError

Time:01-31

I'm trying to:

1 - Generate a list of numbers (specifically RGB colors);

2 - Get a random number from said list;

3 - Select the numbers of that list that are sufficiently distant from this random number;

4 - Get a new random number from this new list.

Rinse and repeat k - 1 times.

This is a MWE:

import math
import random
import seaborn as sns

num_list = list(sns.color_palette('rainbow', 10))

base_num = random.choice(num_list)


def distant_numbers(base_num, num_list, dist):
    
    selectables = []

    for num in num_list:
        if math.dist(base_num, num) >= dist:
            selectables.append(num)
    
    new_base_num = random.choice(selectables)
    
    return distant_numbers(new_base_num, selectables, dist)

But

for k in range(3):
    print(distant_numbers(base_num, num_list, 0.1))

Gives IndexError: list index out of range.

CodePudding user response:

You should try something like this:

def distant_numbers(base_num, num_list, dist, k):
    if k == 0 or len(num_list) < 2:
        return base_num
    selectables = []
    for num in num_list:
        if math.dist(base_num, num) >= dist:
            selectables.append(num)
    new_base_num = random.choice(selectables)
    return distant_numbers(new_base_num, selectables, dist, k-1)

then call function like the following:

for k in range(3):
    print(distant_numbers(base_num, num_list, 0.1, k))

The problem with your code is that the function "distant_numbers" continues to call itself without any stopping point, causing an infinite loop. This leads to the "selectables" list being empty and an error when trying to pick a random number from it. To fix this, you can add an exit point to the function where it returns "new_base_num" if the "selectables" list is less than 2 in length. Additionally, you can also limit the number of times the function calls itself by including a parameter to keep track of the recursion count.

  • Related