Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

# 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.

>Solution :

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)]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading