Random Prime Generation and Replacement

  • Share this:

Code introduction


This function uses the random module to generate prime numbers within a certain range and stores them in a queue. It then randomly removes a certain number of primes and replaces them with new random primes.


Technology Stack : Python, random, collections.deque, pytest.approx

Code Type : Function

Code Difficulty : Intermediate


                
                    
def random_module_usage():
    import random
    from collections import deque
    from pytest import approx

    def get_random_number(min_value, max_value):
        return random.randint(min_value, max_value)

    def is_prime(number):
        if number < 2:
            return False
        for i in range(2, int(approx(number ** 0.5)) + 1):
            if number % i == 0:
                return False
        return True

    def prime_numbers_in_range(min_value, max_value):
        prime_queue = deque([i for i in range(min_value, max_value + 1) if is_prime(i)])
        while prime_queue:
            prime = prime_queue.popleft()
            yield prime
            # Generate a random number of primes to remove and replace with new primes
            num_primes_to_remove = random.randint(1, len(prime_queue) // 2)
            for _ in range(num_primes_to_remove):
                prime_queue.append(random.randint(min_value, max_value))

    return list(prime_numbers_in_range(1, 100))