Guest User

Untitled

a guest
May 17th, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. import random
  2.  
  3. population = 200
  4. generations = 0
  5. mutation = 0.01
  6.  
  7. alphabet = "abcdefghijklmnopqrstuvwxyz! "
  8. target = "subscribe to howcode!"
  9. output = ""
  10. data = []
  11. pool = []
  12. score_range = []
  13.  
  14. class Item:
  15. def __init__(self, data, target):
  16. self.target = target
  17. self.data = data
  18. self.score = self.get_score()
  19.  
  20. def get_score(self):
  21. score = 0
  22. for i in range(len(self.data)):
  23. if self.data[i] == self.target[i]:
  24. score += 1
  25. return score / len(self.data)
  26.  
  27. def __str__(self):
  28. return 'String: ' + ''.join(self.data) + ', Score: ' + str(self.score)
  29.  
  30. # SETUP
  31. for i in range(population):
  32. data.append(Item([random.choice(alphabet) for item in [0] * len(target)], target))
  33.  
  34. while output != target:
  35.  
  36. pool = []
  37.  
  38. # SELECTION
  39. for item in data:
  40. if item != 0:
  41. for i in range(int(item.score * 100)):
  42. pool.append(item)
  43.  
  44. # REPEAT
  45. # PICK 2 PARENTS
  46. # CROSSOVER
  47. # MUTATION
  48. # ADD NEW CHILD TO POPULATION
  49.  
  50. data = []
  51. while len(data) < population:
  52. parentA = pool[random.randint(0,len(pool)-1)]
  53. parentB = pool[random.randint(0,len(pool)-1)]
  54.  
  55. parentAScore = int(parentA.score / (parentA.score + parentB.score) * 100)
  56. parentBScore = int(parentB.score / (parentA.score + parentB.score) * 100)
  57.  
  58. childData = []
  59. for i in range(len(target)):
  60. choice_list = [parentA.data[i]] * int(parentAScore) + [parentB.data[i]] * int(parentBScore)
  61. childData.append(random.choice(choice_list))
  62.  
  63. for i in range(len(childData)):
  64. m = mutation * 100
  65. r = random.randint(0,100/m)
  66. if r == 0:
  67. childData[i] = random.choice(alphabet)
  68.  
  69. child = Item(childData, target)
  70. data.append(child)
  71. output = "".join(child.data)
  72. if output == target:
  73. break
  74. best = None
  75. for i in range(len(data)):
  76. if best == None:
  77. best = data[i]
  78. elif data[i].score > best.score:
  79. best = data[i]
  80. print(best)
  81. generations += 1
  82. print("Generation: " + str(generations))
Add Comment
Please, Sign In to add comment