Skip to content

Instantly share code, notes, and snippets.

@Motoma
Created February 16, 2011 01:21
Show Gist options
  • Select an option

  • Save Motoma/828655 to your computer and use it in GitHub Desktop.

Select an option

Save Motoma/828655 to your computer and use it in GitHub Desktop.
#! /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
@schlamar
Copy link

schlamar commented Aug 2, 2012

  • there is random.choice
  • NUM_OFFSPRING must be converted to int
  • sum([1] * len(chromo)) is the same as len(chromo)

@Motoma
Copy link
Author

Motoma commented Aug 2, 2012

  • Yes, I should have used that.
  • Woops, a hasty mistake, nice catch.
  • You're right here too, but this was a deliberate action. What [1] * len(chromo) does is generate the template gene we are matching against. I felt this was more expressive, but I can see how it is confusing.

I've applied changes for the first two, thanks for the suggestions!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment