The problem
I am working towards improving my Python coding. I am checking that I am doing the best in terms of the Python code, not necessarily the algorithms. Having looked at one of my previous attempts in C++, I learned about Sieves for prime numbers.
I want to know that I am following the proper Python coding "standards" (i.e. PEP8), and there aren't any weird issues I'm overlooking. The run times in comment blocks show the function's run time with my computer, and your results may vary.
The code
"""Prime number generator"""
import math
import argparse
import datetime
def is_odd(number: int):
"""Returns true if the integer passed is an odd number"""
return number % 2 == 1
def is_prime(number: int):
"""Returns true if the integer passed is a prime number"""
for _ in range(2, int(math.sqrt(number)) + 1):
if number % _ == 0:
return False
return True
# Run time: 11.808096
# Params: minimum=40, maximum=999999
def is_sieved(minimum: int, maximum: int, count: bool):
"""Return list of numbers that are prime"""
initial_list = range(minimum, maximum)
list_of_primes = set(initial_list)
for x in range(2, int(math.sqrt(maximum)) + 1):
first_loop_of_numbers = True
for y in range(x, maximum + 1, x):
if not first_loop_of_numbers:
list_of_primes.discard(y)
first_loop_of_numbers = False
print(f"{list_of_primes=}")
if count:
print(f"Primes found: {len(list_of_primes)}")
# Run time: 02.103035 (min 2 | max 999999)
# Run time: 25.752799 (min 2 | max 9999999)
def main(minimum: int, maximum: int, count: bool):
"""Main function"""
if minimum <= 1:
print("Warning: Minimum set to less than 2. Setting to 2...")
minimum = 2
if is_odd(maximum):
maximum = maximum + 1
# Maximum must be even for range() to include it
if minimum >= maximum:
print("Error! Maximum must be an integer higher than Minimum! Current"
+ f"values: {minimum=} | {maximum=}")
return 2
# for number in range(minimum, maximum, 2):
# if is_prime(number):
# print(f"{number}", end=", ", flush=True)
is_sieved(minimum, maximum, count)
print()
return 0
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Prime number generator")
parser.add_argument('--minimum', dest='minimum', type=int, default=2,
help='Minimum number to check (default: 2)')
parser.add_argument('--maximum', dest='maximum', type=int, default=100,
help='Minimum number to check (default: 100)')
parser.add_argument('--count', dest='count', action='store_true',
help="Count the number of primes found")
args = parser.parse_args()
begin_time = datetime.datetime.now()
main(args.minimum, args.maximum, args.count)
end_time = datetime.datetime.now()
print(f"Execution time: {end_time - begin_time}")