[python]Check if randomly generated number is a prime with decorator

In this script a random number is generated, before the number is passed the number is checked if it is a prime number if it is then the number is passed.
I can either do this with calling a function that checks for prime number validity or use a decorator.

A decorator is a function that takes in a function as an argument, the purpose is to add on additional function while maintaining the original function intact.

A wrapper processes the original function’s return value, and return back to the function with return wrapper, if the wrapper function is not returned then the value returned will be None.

from random import randrange


# Decorator is_prime
def is_prime(f):
    # This wrapper adds on prime number checking on randomly generated number.
    # returns a boolean and prime number, if boolean is false then no prime number
    # i.e. None.
    def wrapper(*args):
        # the function has to return a value to use this wrapper.
        num = f(*args)
        # 1 and even numbers are not prime.
        if num <= 1 or num % 2 == 0:
            return False, num
        # 2 is the only even number that is a prime number
        elif num == 2:
            return True, num

        else:
            # Test if any odd number has found a factor between 3 and 1 + sqrt(num).
            for i in range(3, 1 + int(num**0.5), 2):
                if num % i == 0:
                    # a divisor other than 1 and itself is found hence not prime.
                    return False, num
        # anything else is a prime number
        return True, num
    return wrapper


@is_prime
def get_prime(start, stop):
    return randrange(start, stop)


if __name__ == '__main__':
    state = False
    prime_nums = list()
    # Keep finding a prime number between 2 and 100
    while not state:
        state, num = get_prime(2, 100)
    print(f"{num} is found amongst the random numbers.")

prime1prime2prime3prime4

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s