-5

I am not able to remove composite numbers from a list in python 3 .Can you help?

Example input:

list1 = [2, 3, 6, 7, 14, 21, 23, 42, 46, 69, 138, 161, 322, 483]

Expected output:

list1 = [2, 3, 7, 23]

Thanks in advance.

  • 6
    What have you tried? I would start by creating a method which will return if a number is composite or not – apomene Jun 28 '18 at 14:15
  • 1
    Why are you not able? What have you tried? – roganjosh Jun 28 '18 at 14:15
  • 1
    Try to check prime – Manoj Kumar Dhakad Jun 28 '18 at 14:17
  • Also, [do **not** put "thanks" in posts](https://meta.stackexchange.com/questions/2950/should-hi-thanks-taglines-and-salutations-be-removed-from-posts). – user202729 Jun 28 '18 at 14:18
  • [What is the best algorithm for checking if a number is prime?](https://stackoverflow.com/questions/1801391/) – user202729 Jun 28 '18 at 14:20
  • @apomene I am a beginner and was stuck for two hours here. my method was not working as expected. – Harnoor Singh Jun 28 '18 at 15:43
  • @roganjosh because i am a beginner. i tried to iterate through the list and check if the number is prime. the latter part didn't work as expected. i tried to alter it, but in vain – Harnoor Singh Jun 28 '18 at 15:48
  • @user202729 i will take care of that. this was my first question, so i am not familiar to the rules here – Harnoor Singh Jun 28 '18 at 15:50
  • Being a beginner is absolutely fine, but you will get a better reception if you show what you tried beforehand. I'm not a downvoter so I can only guess at their reasons. Even if it's completely broken; it does show that you actually tried _something_ to address your issue, and it gives a basis to explain why that logic didn't work. – roganjosh Jun 28 '18 at 15:51
  • @roganjosh ok. i will do that in my next questions. – Harnoor Singh Jun 28 '18 at 16:01

2 Answers2

0

You can use a list comprehension with all:

list1 = [2, 3, 6, 7, 14, 21, 23, 42, 46, 69, 138, 161, 322, 483]
new_result = [i for i in list1 if all(i%c != 0 for c in range(2, i))]

Output:

[2, 3, 7, 23]
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
0

Ajax1234's solution is correct, but instead of using range(2, i), I would add the modification that range(2, i) becomes range(2, 1+math.ceil(math.sqrt(i))), where the math module has been imported. For very large lists, this reduces the execution time since all composite numbers have factors less than or equal to 1+math.ceil(math.sqrt(i)).

Joel
  • 1,564
  • 7
  • 12
  • 20