Get a list of prime numbers in python 3 - python

Beginner. I'm trying to return a list that includes all the prime numbers from 0 to num. Could someone please help me find what's wrong with my code? I always get an empty list. Thanks a lot! (I'm using python 3.6)
def task(num):
num = int(num)
lst = []
if num < 3:
return lst
else:
for i in range(3,num):
if not i & 1:
lst = lst
else:
primetest = range(3, int(i ** 0.5) + 1, 2)
for n in primetest:
if i % n != 0:
lst.append(i)
return lst
task(5)
Updates:
Thank you guys for all your comments! Really helpful.
This is what my revised code looks like.
def task(num):
num = int(num)
lst = []
if num < 2:
return lst
if num >= 2:
lst.append(2)
for i in range(3, num + 1):
if i % 2 == 1:
switch = True
for n in range(3, int(i ** 0.5) + 1, 2):
if i % n == 0:
switch = False
break
if switch:
lst.append(i)
return lst

The main problem lies with your inner for loop :
With your code you will append the list with i each time you find a number in the primetestrange that is not a divisor of i.
You might want to use a boolean here to store the fact that you found a divisor of i, then only append it to the list if you didn't.
To answer your question, your list is empty because the primetestrange is always empty in your example :
int(3**0.5) + 1 = 3 and int(5**0.5) + 1 = 3
range(3,3,2) = []
The array is empty because the range function will not include the upper limit, and since the inner loop is not doing what it should be expected to do in your code, the result will be an empty list until the parameter of the task function is superior or equal to 9

Your code gets it wrong on several counts, tell me if you understand why the following works?
def task(num):
num = int(num)
lst = [2]
if num < 3:
return lst
for i in range(3, num + 1):
if i % 2 == 1:
for n in range(3, int(i ** 0.5) + 1, 2):
if i % n == 0:
break
else:
lst.append(i)
return lst
(note: the for else clause is quite natural here, for else clauses are used when you search for something in a loop, you break when you find that something, if not break is encountered and the regular stopIteration is used to exit the loop the else part is performed, I say it is natural here since in pseudo code you would say something like "if my number can be divided by another number less than its square it is not prime, otherwise add it to the list of primes" see http://book.pythontips.com/en/latest/for_-_else.html for more detauls)
Its by no means a fast way to do it but I tried to stay as close to the spirit of your attempt while improving the aesthetics of the code

you can find prime numbers and the most dividable one in a dateset.`
a=[ int(x) for x in input("Enter 10 values: ").split() ]
c=[]
prime=[]
b=max(a)
for num in range(1,b+1):
for i in range(2,num):
if (num%i)==0:
break
else:
prime.append(num)
for i in a:
for j in prime:
if i%j==0:
c.append(i)
from collections import Counter
e=Counter(c)
f=e.most_common(1)
f

def prim(z):
lst = []
for i in range(2, z+1):
for j in range(2,i):
if i % j == 0:
break
else:
lst = lst + [i]
return lst
print(prim(20))
result:
[2, 3, 5, 7, 11, 13, 17, 19]

Related

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

Python prime list

integer = int(input("Enter an integer: "))
if integer >= 2:
print(2)
for i in range(2, integer + 1): # range 2,3,...,integer (excludes 1)
for j in range(2, i): # we are going to try dividing by these
if i % j == 0: # not prime
break
else: # is prime
print(i)
input:
7
output:
2
3
5
5
5
7
7
7
7
7
output I want:
2
3
5
7
adding more detail to get past error:
It looks like your post is mostly code; please add some more details.
You're printing i for every value of j that doesn't divide it, until you get a value that does divide it and you execute break.
You should only print i when you don't break out of the loop. Put the else: statement on the for loop, not if. This else: statement is executed when the loop finishes normally instead of breaking.
for i in range(2, integer + 1): # range 2,3,...,integer (excludes 1)
for j in range(2, i): # we are going to try dividing by these
if i % j == 0: # not prime
break
else: # is prime
print(i)
Put the print(i) in the outer for loop with a flag that keeps track of the result.
for i in range(2, integer + 1): # range 2,3,...,integer (excludes 1)
isPrime = True
for j in range(2, i): # we are going to try dividing by these
if i % j == 0:
isPrime = False
break
if isPrime:
print(i)
Your logic is slightly wrong. I have added the correct code below with comments :
integer = int(input("Enter an integer: "))
if integer >= 2:
print(2)
for i in range(2, integer + 1): # range 2,3,...,integer (excludes 1)
prime=true #assume that i is prime
for j in range(2, i): # we are going to try dividing by these
if i % j == 0: # not prime
prime=false # we now know it is not prime
break
if prime==true: # if we didn't do prime=0, then it's a prime
print(i)
What you were doing is printing i for every j from 2 to i that did not divide i. But instead, what had to be done is print i only once when none of the j from 2 to i divided i.
Hope you understand the mistake and this clears your doubt !

Which is the most pythonic way for writing a prime number function using for and while loop?

I am about to execute a function which aim is to return a Prime/Not prime statement if its argument is or isn't a prime number. I succeeded using a for loop:
def prime1(n):
z = []
for i in range (1, n+1):
if (n/i).is_integer():
z.append(i)
i=i+1
if len(z) == 2:
print ("Prime")
else:
print ("Not prime")`
Then I tried to do the same but using the while loop:
def prime2(n):
z = []
i = 1
while i < int(len(range(1, n+1))):
if (n/i).is_integer():
z.append(i)
i=i+1
if len(z) == 2:
print ("Prime")
else:
print ("Not prime")
Unfortunately, my system continues to calculating without printing me an output.
Can you explain me where I have made a mistake?
The i = i + 1 does nothing in your for loop, since the value of i is overwritten with the next value of the iterator; effectively, the for loop is performing i = i + 1 for you on every iteration, whether or not i divides n. You need to do the same thing in your while loop:
while i < n + 1:
if (n/i).is_integer():
z.append(i)
i = i + 1
The most pythonic way I could think of is below:
def isPrime(n):
return all(n % i for i in range(2, int(n ** 0.5) + 1)) and n > 1
for i in range(1, 20):
print(isPrime(i))
Explanation:
all makes sure that every item in the given expression returns True
n % i returns True if n != 0 (even negative numbers are allowed)
int(n ** 0.5) is equivalent to sqrt(n) and as range always returns numbers up to n - 1 you must add 1
n > 1 makes sure that n is not 1
The problem in your code is that your i = i + 1 in the wrong scope
Your program checks if (n/i).is_integer() which returns False as n / 2 is not a integer
Improving your code:
Instead of (n/i).is_integer() you can use n % i == 0, which returns the remainder equals 0
Next you must place i = i + 1 in the outer scope
And personally, I was never a fan of i = i + 1. Use i += 1
I think the best way is using the code I have shown above.
Hope this helps!
Edit:
You can make it print 'Prime' or 'Not Prime' as follows:
def isPrime(n):
print('Prime' if all(n % i for i in range(2, int(n ** 0.5) + 1))
and n > 1 else 'Not Prime')
for i in range(1, 20):
isPrime(i)
You are increment the iterable variable i inside the if statement, so the variable is never incremented, stucking on an infinite loop.
When you used for it worked because the iterable changes itself after every full iteration of the block.
Moving the incremenf of i one identation block to the left (inside the while instead of for) will work just fine
Code adapted from https://www.programiz.com/python-programming/examples/prime-number
You don't need to check until num and you can go 2 by 2 if you don't have a database of prime numbers
import math
#num = 437
if num > 1:
# check for factors
for i in range(2, int(math.ceil(math.sqrt(num))), 2):
if (num % i) == 0:
print(num, "is not a prime number")
print(i, "times", num // i, "is", num)
break
else:
print(num, "is a prime number")
# if input number is less than
# or equal to 1, it is not prime
else:
print(num, "is not a prime number")
Our preferred method should not be while loops if we don't need to use them, that being said, we could use list comprehensions:
def prime(n):
z = []
[z.append(i) for i in range(1, n+1) if (n/i).is_integer()]
[print("Prime") if len(z) == 2 else print("Not Prime")]
prime(101)
But lets take a loop at what you got your for loop:
for i in range (1, n+1):
if (n/i).is_integer():
z.append(i)
i=i+1
The line i = i + doesn't serve the purpose you intend, the loop is going to iterate from 1 to n+1 no matter what
Now the while loop:
while i < int(len(range(1, n+1))):
if (n/i).is_integer():
z.append(i)
# i=i+1 does not go inside if statement
i += 1
Now you do need to increment i but if that incrementing only occurs when the if conditions are met, then if the if condition is not met you are going to be stuck at the same i looping over it.
Also try using i += 1 means the same thing

count prime number in a list

In Python 3, I am trying to write a function that counts the number of prime number in a list, can anyone help me with that?
def function(x):
array = []
aa = len(x)
for num in x :
if (num == 1 or num ==2):
array.append()
elif num >2:
for i in range (2, aa):
if (num % i )== 0:
array.append()
else:
print (num)
array.append(num)
return len(array)
z = [4,5,6,7,8,9,10]
print (function(z))
but it shows an incorrect result!
Here is my fix of your code.
def count_primes_in_list(numbers):
primes = []
for num in numbers:
if num == 2:
primes.append(num)
else:
is_prime = True
for i in range(2, num):
if num % i == 0:
is_prime = False
break
if is_prime:
print (num)
primes.append(num)
return len(primes)
z = [4, 5, 6, 7, 8, 9, 10]
print (count_primes_in_list(z))
I'll note a few things for beginners to know. Don't use reserved or type like words for methods and variables, name things descriptively. Change function to count_primes_in_list, array to primes, x to numbers and so on. Your test for a prime is incorrect. A prime is a number greater than 1 that can not be divided by another number greater than 1 and less than its self. In python don't put () around if tests.
Your logic is a little wrong and I'm not sure what you think array.append() is supposed to. And the len(x) is irrelevant. Note: 1 is not prime.
You can use the else: clause to the for loop, this means only execute if the for loop completes so if you break out early it does not get executed. So if the num is divisible by any number break else: add to array.
def function(x):
array = []
for num in x:
if num <= 1:
continue
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)
array.append(num)
return len(array)
In []:
z = [4, 5, 6, 7, 8, 9, 10]
print(function(z))
Out[]:
5
7
2
Note: there are many more efficient methods for checking primality but this is good enough for small numbers.
def countPrime(num):
d=0
for n in num:
if n>1:
for i in range(2,n):
if (n%i)==0:
break
else:
d+=1
return d
if __name__ == '__main__':
num=[]
cot=int(input())
for i in range(cot):
numbers.append(int(input()))
print(countPrime(num))
prime number count in python list
def countPrimeNumbers(numbers):
count=0
for num in numbers:
if(num<2):
continue
else:
for i in range(2,num):
if(num%i==0):
break
else:
count+=1
return count

Python3.x Prime Number List with while loop

def prime(upper):
while upper >=2:
for num in range(2, upper + 1):
prime = True
for i in range(2, num):
if (num % i == 0):
prime = False
if prime:
print(num, end=",")
if num == upper: #I think there is a problem here
break
prime(7)
How can I stop this function when it reachs 7 value
PS: I want to execute this codes with while loop.
BTW if you can make it this codes without for-loop please do it for me :)
I appreciate you...
EDIT:
I guess my previous is_prime function is problematic. This way is quicker and works well:(Source)
def is_prime(n):
""""pre-condition: n is a nonnegative integer
post-condition: return True if n is prime and False otherwise."""
if n < 2:
return False;
if n % 2 == 0:
return n == 2 # return False
k = 3
while k*k <= n:
if n % k == 0:
return False
k += 2
return True
You should use this function.
BEFORE EDIT:
I would use the is_prime function from here. You can use another way.
And, I would suggest this code for you:
def is_prime(Number):
return 2 in [Number, 2**Number%Number]
def prime(upper):
print([num for num in range(2, upper + 1) if is_prime(num)])
prime(7)
Output:
[2, 3, 5, 7]
But if you insist on using only while loop, you can modify your prime function as:
def prime(upper):
num = 2
while num <= upper:
if is_prime(num):
print(num, end = ",")
num += 1
Then, output will be:
2,3,5,7,

Categories