Created
February 16, 2011 01:21
-
-
Save Motoma/828655 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #! /usr/bin/env python | |
| from random import choice, randint | |
| def random_chromosome(): | |
| return [randint(0, 1) for i in range(32)] | |
| def calc_fitness(chromo): | |
| return sum(chromo) | |
| def mate(chromo1, chromo2): | |
| return mutate(chromo1[:16] + chromo2[16:]) | |
| def mutate(chromo): | |
| for i in range(2): | |
| chromo[randint(0, 31)] = randint(0, 1) | |
| return chromo | |
| def alphas(arrs): | |
| decorated = [(calc_fitness(chromo), chromo) for chromo in arrs] | |
| decorated.sort(reverse = True) | |
| return [chromo[1] for chromo in decorated][:10] | |
| def is_spartan(chromo): | |
| return sum(chromo) == sum([1] * len(chromo)) | |
| if __name__ == '__main__': | |
| from time import asctime as time | |
| from sys import argv | |
| if len(argv) < 2: | |
| NUM_OFFSPRING = 20 | |
| else: | |
| NUM_OFFSPRING = int(argv[1]) | |
| SPARTAN = [1] * 32 | |
| SEEDS = [random_chromosome() for i in range(NUM_OFFSPRING)] | |
| top10 = alphas(SEEDS) | |
| i = 0 | |
| while not SPARTAN in top10: | |
| print("*** ALPHAS FROM GENERATION: #%i ***" % (i)) | |
| offspring = [] | |
| for j in range(NUM_OFFSPRING): | |
| offspring.append(mate(choice(top10), choice(top10))) | |
| top10 = alphas(offspring) | |
| print(top10) | |
| i += 1 |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I've applied changes for the first two, thanks for the suggestions!