Welcome, guest | Sign In | My Account | Store | Cart

This is an evolutionary algorithm that returns a random list of prime numbers. This code is highly inefficient for a reason. This algorithm is more of a proof of concept that if a prime was a heritable trait, it would not be a desired one.

Parameters:

isPrime --> n: number to check if it is prime allPrimes --> n: size of list of random primes, m: the primes in the list will be between 0 and m

Python, 33 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
from random import sample, randint

def isPrime(n):
    if n == 1:
        return 0
    else:
        for x in range(2, int(n ** 0.5) + 1):
            if n % x == 0:
                return 0
        return 1

isPrimeList = lambda n: [isPrime(i) for i in n]

def allPrimes(n, m):
    randBinList = lambda x: [randint(1, m) for b in range(1, x + 1)]
    parentA = randBinList(n)
    parentB = randBinList(n)
    while True:
        amount1 = randint(1, n)
        amount2 = randint(1, n)
        childA = sample(parentA, amount1)
        childA.extend(sample(parentB, n - amount1))
        childB = sample(parentA, amount2)
        childB.extend(sample(parentB, n - amount2))
        print(childA)
        print(childB)
        parentA = childA
        parentB = childB
        if all(isPrimeList(childA)) or all(isPrimeList(childB)):
            break
        elif any(isPrimeList(childA + childB)) == False:
            parentA = randBinList(n)
            parentB = randBinList(n)

This code really shouldn't be used to find a list of random prime numbers. There are other very efficient algorithms. I will post one. This algorithm should be used for educational purposes as to how a genetic algorithm works. This algorithm is also a proof of concept that if primes numbers were heritable traits, they would be undesirable. You can tell this if you set the size of the list (n) to a large number and m to a large number, the program will run for a very long time. I also have the function print out each list on purpose. It is really cool to see how the list evolves.

Example:

>>> allPrimes(5,20)
[12, 19, 17, 6, 8]
[12, 1, 10, 17, 6]
[19, 6, 12, 8, 12]
[19, 12, 17, 8, 1]
[8, 6, 8, 1, 12]
[12, 8, 8, 19, 17]
[1, 8, 19, 17, 8]
[12, 8, 17, 8, 19]
[17, 19, 12, 8, 8]
[1, 8, 19, 8, 17]
[12, 8, 17, 8, 19]
[17, 1, 19, 17, 8]
[17, 19, 8, 8, 19]
[17, 8, 19, 17, 8]
[19, 8, 17, 19, 17]
[19, 8, 19, 17, 8]
[19, 19, 17, 17, 8]
[19, 19, 8, 8, 19]
[19, 17, 8, 19, 19]
[17, 17, 8, 19, 19]
[19, 8, 17, 19, 19]
[19, 17, 17, 19, 8]
[19, 19, 17, 19, 17]
[8, 19, 19, 19, 19]
The Random Prime List is: [19, 19, 17, 19, 17]