1

I am trying to learn Python, but I'm still quite new at it. I am attempting to create a list of numbers from 2 up to the number that the user will input and go through the list and remove all non-prime numbers from that list, then print it back out. I am having trouble calculating since I keep getting the error: list index is out of range. I was thinking of using a for loop but then the variable i would be lower than variable current and I need to make sure i is always higher than current as it goes through the list. I am only allowed to use basic functions and loops for the task.

counter = 2

current = 2

n = int( input( "Please enter a number larger than 2. " ) )

while counter <= n:
    userList.append( counter )
    counter = counter + 1

print( "Printing out list " )
print( userList )

i = 1

while i <= len( userList ):
    if userList[ i ] % current == 0:
        userList.remove( userList[i] )
        i = i + 1
    else:
        current = current + 1

print( userList )

1 Answers1

0

There are some mistakes in your code.

1) Removing from large list is very slow, because you need to move everything after the item that was removed to avoid any gap between items in list. It's better to mark item as removed and then just print whatever left in there.

2) By using your algorithm, you need two while loops.

3) If you have got list with N items, than the last index of list is (N-1).

More Pythonic solution:

#!/usr/bin/env python3

n = int(input("Maximal number: "))
numbers = list(range(2, n+1))

i = 0
while i < len(numbers):
    if numbers[i] != None:
        j = i + 1
        while j < len(numbers):
            if numbers[j] != None:
                if numbers[j] % numbers[i] == 0:
                    numbers[j] = None
            j += 1
    i += 1

print(list(filter(lambda x: x is not None, numbers)))`
gcx11
  • 128
  • 4
  • I understand. The task is only allowing me to use basic loops and functions however. Using keywords such as filter and lambda are not allowed. I don't even know what they do. Basically, I am only allowed to use what I have in my code, it just isn't correct. – kinetic_shadow Apr 16 '17 at 00:35
  • Basically, you just create new list from values that aren't marked as removed. You can easily rewrite it as one for loop and if statement. – gcx11 Apr 16 '17 at 00:49