mardi 21 février 2023

Why is this error(list index out of range) generated and how to fix it?

I run this program several times, sometimes it doesn't give an error, sometimes it gives this error.I wonder why this is happening? and how to fix it?

I run this program in Pycharm,and I use archlinux.

Below is my entire code:

#!/usr/bin/env ipython3

import random


class Animal:
    """a baseclass for special animal."""

    def __init__(self, species, priority):
        self._species = species
        self._priority = priority

    def get_species(self):
        return self._species

    def get_priority(self):
        return self._priority

    def animal_compete(self, other):
        if self.get_priority == other.get_priority:
            return False
        elif self.get_priority > other.get_priority:
            return True


class Bear(Animal):
    """Bear class."""

    def __init__(self):
        super().__init__("bear", 1)


class Fish(Animal):
    """Fish class."""

    def __init__(self):
        super().__init__("fish", 0)


class Ecosystem:
    """Ecosystem class."""

    def __init__(self, scale=100):
        self._animals_index = []
        self._None_index = [j for j in range(scale)]
        self._river = [None] * scale

    def get_animals_index(self):
        return self._animals_index

    def get_river(self):
        return self._river

    def get_None_index(self):
        return self._None_index

    def add_animal(self, animal_instance, index=None):
        """if index = None,add a new animal randomly into the river, otherwise put the animal into the index."""
        if index is None:
            new_animal_index = random.choice(self.get_None_index())
            if animal_instance.get_priority() == 0:
                new_fish = Fish()
                self._river[new_animal_index] = new_fish
            if animal_instance.get_priority() == 1:
                new_bear = Bear()
                self._river[new_animal_index] = new_bear
            self._None_index.remove(new_animal_index)
            self._animals_index.append(new_animal_index)
        else:
            self._river[index] = animal_instance
            self._None_index.remove(index)
            self._animals_index.append(index)

    def delete_animal(self, index):
        """delete the animal."""
        self._animals_index.remove(index)
        self._river[index] = None
        self._None_index.append(index)

    def replace_animal(self, animal1_index, animal2_index):
        """replace animal2 with animal1"""
        self._river[animal2_index] = self._river[animal1_index]
        self._animals_index.remove(animal1_index)

        self._river[animal1_index] = None
        self._None_index.append(animal1_index)


if __name__ == "__main__":
    test_ecosystem = Ecosystem()
    for i in range(20):
        test_ecosystem.add_animal(Fish())
        test_ecosystem.add_animal(Bear())
    loop_count = 0
    animals = sorted(test_ecosystem.get_animals_index())
    none_index = sorted(test_ecosystem.get_None_index())
    while len(animals) < 90:
        for animal in animals:
            river = test_ecosystem.get_river()
            step = random.randint(-1, 1)
            if step != 0:
                if 0 < animal + step < len(test_ecosystem.get_river()):
                    if river[animal + step] is None:
                        test_ecosystem.add_animal(river[animal], animal + step)
                    if isinstance(river[animal + step], Animal):
                        if (
                            river[animal].get_priority()
                            > river[animal + step].get_priority()
                        ):
                            test_ecosystem.replace_animal(animal, animal + step)
                        elif (
                            river[animal].get_priority()
                            == river[animal + step].get_priority()
                        ):
                            test_ecosystem.add_animal(river[animal])
        animals = sorted(test_ecosystem.get_animals_index())
        none_index = sorted(test_ecosystem.get_None_index())
        loop_count += 1


I tried googling when list out of range error happens, and learned that this error is produced when the index is not in the list, but I am more confused why random.choice() produces an value that is not in the list?




Aucun commentaire:

Enregistrer un commentaire