Search code examples
pythonnumpyindex-error

python "IndexError: index 8 is out of bounds for axis 0 with size 8"


The problem requires me to write a function that compiles a list of prime numbers from the output of a given function that gives 2 lists, one list of numbers from 2 to an arbitrary number and a second list that matches the numbers in the first list with "true" or "False" values depending on whether the numbers in the first list are prime or not.

I have no idea whether my code is just fundamentally wrong to answer the question, or if I am on the right track and just made an error...

Any help would be immensely appreciated.

The question:

Write a function (called primes_list) that takes a single input N. This function must make use of the prime_sieve function to compute and return an array (or list) of only prime numbers less than or equal to N+1.

For example, if N=8 this function should return [2,3,5,7]

the given code:

import numpy as np

def prime_sieve(N):
    nums = np.arange(2, N+2, 1)
    mask = []
    for n in nums:
        mask.append(True)
    for n in nums:     
        for i in np.arange(2*n-2, N, n):
            mask[i] = False
    return nums, np.array(mask)

numbers, mask = prime_sieve(8)
print(numbers)
print(mask)

[2 3 4 5 6 7 8 9]
[ True  True False  True False  True False False]

My Code:

import numpy as np

def primes_list(N):
    numbers, mask = prime_sieve(N)
    primes = []
    for n in numbers:
        if mask[n] == "true":
            primes.append(numbers[n])
    return primes

print(primes_list(8))

but this gives an error:

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
 <ipython-input-60-4ea4d2f36734> in <module>
----> 2 print(primes_list(8))

<ipython-input-59-a5080837c5c8> in primes_list(N)
      6     primes = []
      7     for n in numbers:
----> 8         if mask[n] == "true":
      9             primes.append(numbers[n])
     10     return primes

IndexError: index 8 is out of bounds for axis 0 with size 8

Solution

  • Your n, that you use to slice your list mask is a list of numbers that are not suitable for index (since it will always contain N, N+1, while last index of mask is N-1).

    Also, the second list mask contains Bool not str, so your comparison of mask[n] == 'true' will always return False.

    With above points in mind, your primes_list can be:

    def primes_list(N):
        numbers, mask = prime_sieve(N)
        primes = []
        for i, n in enumerate(numbers): # <<< added enumerate 
            if mask[i]:                 # <<< removed unnecessary comparison
                primes.append(n)        # <<< append n directly
        return primes
    

    which returns:

    [2, 3, 5, 7]
    

    as it should be.