I am trying to test if a number is a prime number using list comprehension. This is what?I have done, but not getting the desired results.
number = 20
prime_number_test = [1 if number % i != 0 else 0 for i in range(2, 5)]
output = [0,1,0]
number 20 obviously isn't a prime number. Now if I have a known prime number to test like let say number 19
number = 19
prime_number_test = [1 if number % i != 0 else 0 for i in range(2, 5)]
output = [1,1,1]
Now my question is, why is the first code not all zeros, and what is the best way to achieve this using a list comprehension that my results tells me this is a prime number
the above code show [0,1,0]
because 20 is not divisible by 3 but is divisible by 2 and 4. 19 is not divisible by 2,3 or 4 so it has the output [1,1,1]
You can say that if there are 0 in output then the number is not prime.
you can use the following program to find primes.
num = int(input("Enter a number: "))
if num > 1:
for i in range(2,num):
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")
else:
print(num,"is not a prime number")
Your comprehension would give you a list of values, and you can use the any
function. For example, here a list of True
or False
values is obtained:
number = 20
upper_limit = int(number ** 0.5) # square root
prime_number_test = not any([number % i == 0 for i in range(2, 1 + upper_limit)])
print(prime_number_test)
The list returned by your comprehension is:
[True, False, True]
corresponding to division by 2, 3, and 4.
Then the any
returns True
, which the not
then negates: 20 is not a prime number because it is divisible by 2 and 4.
Here you could also invert the test and do:
prime_number_test = all([number % i != 0 for i in range(2, 1 + upper_limit)])
Note the !=
and the all
.
However, in either case, it is more efficient (in time and memory) if you replace the square brackets with parentheses:
prime_number_test = not any((number % i == 0 for i in range(2, 1 + upper_limit)))
This similar looking expression uses a generator , and instead of building up a list it will generate values on demand and the any
will cause it to iterate as required and stop when the first match is found.
(When using the generator as the sole argument of a function, as here, it is also permissible to omit the outer parentheses.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.