'Code to find primary number in list and return it
I want to define a function to find primary numbers in a list and return the primary number in alist below the code but it returns empty lists. I need help to find what is wrong.
def primes_nums(array):
li=[]
for num in array:
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
elif num == 1:
continue
else:
li.append(num)
print(li)
return li
array=[1, 5, 2, 10]
print(primes_nums(array))
Solution 1:[1]
The main issue with your code is that for any num > 1, you just end up in this part of the code:
for i in range(2, num):
if (num % i) == 0:
break
which actually never adds the number in the list, no matter how all the comparisons end. A possible solution of this might looks something like this:
def primes_nums(array):
li=[]
for num in array:
if num > 1:
is_prime = True
for i in range(2, num):
if (num % i) == 0:
is_prime = False
if is_prime:
li.append(num)
elif num == 1:
continue
return li
array=[1, 5, 2, 10]
print(primes_nums(array))
Also, you do not need to use li=li.append(num), as append just modifies the existing list.
Solution 2:[2]
Surprisingly, all you need to do is move the "else" so it is part of the "for". The "else" clause of a "for" statement gets executed if you get all the way through the loop without using "break". In this case, that only happens if you try all of the factors and none of them matches.
Also note that you don't have to search all the way to num. You can stop at num//2. Technically, you can stop at math.sqrt(num)+1, but that's an optimization for later.
def primes_nums(array):
li=[]
for num in array:
if num > 1:
for i in range(2, num//2+1):
if (num % i) == 0:
break
else:
li.append(num)
elif num == 1:
continue
print(li)
return li
Solution 3:[3]
Using what you have, here is a simple revision that finds the primes and prints them out in a list, with each prime printed only once.
def primes_nums(array):
li=[]
for num in array:
for i in range(2, num):
if i == num or num % i == 0:
break
else:
if num not in li:
li.append(num)
print(li)
array=[1, 2, 3, 5, 7, 10]
primes_nums(array)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 |
