Guest User

Genetic Algorithm Demo Version1

a guest
Aug 8th, 2010
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.56 KB | None | 0 0
  1. #Genetic Algorithm Demo Version1
  2. #By Nicolas Far nicofff (at) gmail.com
  3. #August 2010
  4.  
  5. import random
  6.  
  7. def getRandomChar():
  8.     RG=random.Random()
  9.     return chr(RG.randint(ord('a'),ord('z')))
  10.  
  11. def getRandomInt(maxim):
  12.     RG=random.Random()
  13.     return RG.randint(0,maxim-1)
  14.  
  15. class Schromosome:
  16.     def __init__(self,slen,string=''):
  17.         if string!='':
  18.             self.string=string
  19.             return
  20.         self.string=""
  21.         for i in range(slen):
  22.             self.string+=getRandomChar()
  23.  
  24.     def fitness(self,string):
  25.         result=0
  26.         for i in range(len(string)):
  27.             result+=abs(ord(string[i])-ord(self.string[i]))
  28.         return result
  29.  
  30.     def clone(self):
  31.         result=""
  32.         position=getRandomInt(len(self.string))
  33.         for i in range(len(self.string)):
  34.             if i != position:
  35.                 result+=self.string[i]
  36.             else:
  37.                 result+=getRandomChar()
  38.         return result
  39.  
  40. pop=50
  41. population=[]
  42. endString='holamundo'
  43. for i in range(pop):
  44.     population.append(Schromosome(len(endString)))
  45. population.sort(key=lambda guy: guy.fitness(endString))
  46.  
  47. iteration=0
  48. while True:
  49.     guy=population[getRandomInt(pop)]
  50.     prev=guy.fitness(endString)
  51.     new=prev
  52.     while prev<=new:
  53.         newguy=Schromosome(0,guy.clone())
  54.         new=newguy.fitness(endString)
  55.     population[pop-1]=newguy
  56.     population.sort(key=lambda guy: guy.fitness(endString))
  57.     print ('iteration:',iteration,'best:',population[0].string)
  58.     iteration+=1
  59.     if newguy.string==endString:
  60.         break
Advertisement
Add Comment
Please, Sign In to add comment