Improved and shortened prime_check.py (#3454)

* Made small improvements and shortened prime_check.py

* improved descriptions on tests in prime_check.py

* Ran black and isort
This commit is contained in:
Rolv Apneseth 2020-10-23 17:17:29 +01:00 committed by GitHub
parent c2b7acdf11
commit 04fae4db9b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -5,25 +5,20 @@ import unittest
def prime_check(number: int) -> bool: def prime_check(number: int) -> bool:
""" """Checks to see if a number is a prime.
Check to See if a Number is Prime.
A number is prime if it has exactly two dividers: 1 and itself. A number is prime if it has exactly two factors: 1 and itself.
""" """
if number < 2:
# Negatives, 0 and 1 are not primes if 1 < number < 4:
return False
if number < 4:
# 2 and 3 are primes # 2 and 3 are primes
return True return True
if number % 2 == 0: elif number < 2 or not number % 2:
# Even values are not primes # Negatives, 0, 1 and all even numbers are not primes
return False return False
# Except 2, all primes are odd. If any odd value divide odd_numbers = range(3, int(math.sqrt(number) + 1), 2)
# the number, then that number is not prime. return not any(not number % i for i in odd_numbers)
odd_numbers = range(3, int(math.sqrt(number)) + 1, 2)
return not any(number % i == 0 for i in odd_numbers)
class Test(unittest.TestCase): class Test(unittest.TestCase):
@ -40,12 +35,17 @@ class Test(unittest.TestCase):
self.assertTrue(prime_check(29)) self.assertTrue(prime_check(29))
def test_not_primes(self): def test_not_primes(self):
self.assertFalse(prime_check(-19), "Negative numbers are not prime.")
self.assertFalse( self.assertFalse(
prime_check(0), "Zero doesn't have any divider, primes must have two." prime_check(-19),
"Negative numbers are excluded by definition of prime numbers.",
) )
self.assertFalse( self.assertFalse(
prime_check(1), "One just have 1 divider, primes must have two." prime_check(0),
"Zero doesn't have any positive factors, primes must have exactly two.",
)
self.assertFalse(
prime_check(1),
"One only has 1 positive factor, primes must have exactly two.",
) )
self.assertFalse(prime_check(2 * 2)) self.assertFalse(prime_check(2 * 2))
self.assertFalse(prime_check(2 * 3)) self.assertFalse(prime_check(2 * 3))