Gregory Arnold
Gregory Arnold

Reputation: 1

Python 3.x - Cannot fix error: "slice indices must be integers or None or have an __index__ method" + more

I'm working on a class that replicates the Sieve of Eratosthenes and have been getting the error message given in the title. Below is my code, more questions follow.

    class Sieve:

def __init__(self, max):
    if max < 0:
        raise RuntimeError
    else:
        self.numbers = [([False] * 2) + ([True] * (max - 1))]

def findPrimes(self):
    for i in self.numbers:
        if self.numbers:
            for j in self.numbers[i:]:
                if j % i == 0:
                    self.numbers[j] = False
                else:
                    None
        else:
            None

def howMany(self):            ##Must use reduce
    reduce((lambda i: True if numbers else False), self.numbers, self.numbers[2:])

def toList(self):
    T = [L[i] for i in self.numbers]
    return print(self.numbers)

So in the function findPrimes(self), specifically on line 14, I get the error message described in the title. What exactly is the source of the problem?

Additionally I want to ask a few questions about my methods. In findPrimes, I'm trying to visit each element of the list. If it is true, I want to take the index number (i) and visit all other indexes that are multiples of i (i, i+i, i+i+i, etc). I haven't tested this completely yet, but I feel like my syntax is wrong. Any help is appreciated.

Finally, I need to use a reduce function in the method howMany in order to determine how many elements of the list are true, and return that number. Again, any knowledge on the topic is greatly appreciated.

Thank you everyone :)

Upvotes: 0

Views: 122

Answers (1)

WSQ
WSQ

Reputation: 53

In python, for i in self.numbers works like Java enhanced For loop, where the For loop will iterate over the list, i will be the list entry (In your case, True / False) instead of the index.

If you want to access the list index, please utilize for i in range(len(self.numbers)), i will then loop from 0 to (length of list - 1).

Upvotes: 1

Related Questions