Home > Mobile >  Given a list of numbers, how can I remove all multiples of primes (but not primes)?
Given a list of numbers, how can I remove all multiples of primes (but not primes)?

Time:02-11

I am starting on my Python journey and am doing some exercises to get the hang of it all. One question is really giving me troubles as I do not understand how to complete it.

Question: Given a list of natural numbers, remove from it all multiples of 2 (but not 2), multiples of 3 (but not 3), and so on, up to the multiples of 100, and print the remaining values.

From this question I take it that I should first make a list with all prime numbers and after that append the values that correspond to a new list. This is what I have until know:

# Read list:
a = [5, 6, 7, 8, 9]

# First get a list with all primes
primes = []
for i in range(0, 101):
    for j in range(2, int(i ** 0.5)   1):
         if i%j == 0:
             break
    else:
        primes.append(i)

# Next append to new list
b = []
for num in a:
    for prime in primes:
        if num == prime and num % prime == 0:
            b.append(num)  
print(b)

Now this works for this simple example, but upon testing it on another set (one of which I do not know the input values of the test case), my output is:

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

Which is my original list with the prime numbers. So somewhere along the line I am making a mistake and I cannot see the logic behind it. Any help would be greatly appreciated.

CodePudding user response:

To solve the task all you need to do is filter out the numbers by using a generator and a for loop, which by itself is already finding the prime numbers

a = [5,6,7,8,9]
for i in range(2,101):
    a = [j for j in a if (j==i or j%i!=0)]
  • Related