Verify that the target contains no genes besides the ones inside genes variable. >>> from string import ascii_lowercase >>> basic("doctest", ascii_lowercase, debug=False)[2] 'doctest' >>> genes = list(ascii_lowercase) >>> genes.remove("e") >>> basic("test", genes) T
(target: str, genes: list[str], debug: bool = True)
| 95 | |
| 96 | |
| 97 | def basic(target: str, genes: list[str], debug: bool = True) -> tuple[int, int, str]: |
| 98 | """ |
| 99 | Verify that the target contains no genes besides the ones inside genes variable. |
| 100 | |
| 101 | >>> from string import ascii_lowercase |
| 102 | >>> basic("doctest", ascii_lowercase, debug=False)[2] |
| 103 | 'doctest' |
| 104 | >>> genes = list(ascii_lowercase) |
| 105 | >>> genes.remove("e") |
| 106 | >>> basic("test", genes) |
| 107 | Traceback (most recent call last): |
| 108 | ... |
| 109 | ValueError: ['e'] is not in genes list, evolution cannot converge |
| 110 | >>> genes.remove("s") |
| 111 | >>> basic("test", genes) |
| 112 | Traceback (most recent call last): |
| 113 | ... |
| 114 | ValueError: ['e', 's'] is not in genes list, evolution cannot converge |
| 115 | >>> genes.remove("t") |
| 116 | >>> basic("test", genes) |
| 117 | Traceback (most recent call last): |
| 118 | ... |
| 119 | ValueError: ['e', 's', 't'] is not in genes list, evolution cannot converge |
| 120 | """ |
| 121 | |
| 122 | # Verify if N_POPULATION is bigger than N_SELECTED |
| 123 | if N_POPULATION < N_SELECTED: |
| 124 | msg = f"{N_POPULATION} must be bigger than {N_SELECTED}" |
| 125 | raise ValueError(msg) |
| 126 | # Verify that the target contains no genes besides the ones inside genes variable. |
| 127 | not_in_genes_list = sorted({c for c in target if c not in genes}) |
| 128 | if not_in_genes_list: |
| 129 | msg = f"{not_in_genes_list} is not in genes list, evolution cannot converge" |
| 130 | raise ValueError(msg) |
| 131 | |
| 132 | # Generate random starting population. |
| 133 | population = [] |
| 134 | for _ in range(N_POPULATION): |
| 135 | population.append("".join([random.choice(genes) for i in range(len(target))])) |
| 136 | |
| 137 | # Just some logs to know what the algorithms is doing. |
| 138 | generation, total_population = 0, 0 |
| 139 | |
| 140 | # This loop will end when we find a perfect match for our target. |
| 141 | while True: |
| 142 | generation += 1 |
| 143 | total_population += len(population) |
| 144 | |
| 145 | # Random population created. Now it's time to evaluate. |
| 146 | |
| 147 | # (Option 1) Adding a bit of concurrency can make everything faster, |
| 148 | # |
| 149 | # import concurrent.futures |
| 150 | # population_score: list[tuple[str, float]] = [] |
| 151 | # with concurrent.futures.ThreadPoolExecutor( |
| 152 | # max_workers=NUM_WORKERS) as executor: |
| 153 | # futures = {executor.submit(evaluate, item, target) for item in population} |
| 154 | # concurrent.futures.wait(futures) |