Advertisement
Guest User

Untitled

a guest
Jul 22nd, 2019
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.72 KB | None | 0 0
  1. import random
  2.  
  3. wt = [15,3,2,5,9,20]
  4. pt = [15,7,10,5,8,17]
  5. par = ["100110","001110","010100","011001"]
  6. score = [0,0,0,0]
  7. weight= [0,0,0,0]
  8. print("Parents:")
  9. print(par)
  10.  
  11. def fitScore(chrom):
  12. x = 0
  13. y = 0
  14. for i in range(0,6):
  15. if chrom[i] is "1":
  16. x+= wt[i]
  17. y+= pt[i]
  18. return x, y
  19. """
  20. while 1:
  21. x = input(">>")
  22. print("weight,point")
  23. print(fitScore(str(x)))
  24.  
  25. """
  26.  
  27.  
  28.  
  29. def minAndBetter(scr):
  30. d = score[0]
  31. temp = 0
  32. flag = 0
  33. for i in range(0,4):
  34. print(score[i])
  35. if score[i]<d and score[i]<scr:
  36. d = score[i]
  37. temp = i
  38. flag = 1
  39. if flag==1:
  40. print("replaced a",temp,d)
  41. return temp
  42. else:
  43. t = random.randint(0,3)
  44. print("replaced b", t)
  45. return t
  46.  
  47.  
  48. i=1
  49. while (i<4):
  50. print("Generation#",i)
  51. # fitness score all
  52. for j in range(0,4):
  53. weight[j],score[j] = fitScore(par[j])
  54. print(par[j],weight[j],score[j])
  55.  
  56. # Selection
  57. t1 = random.randint(0,3) # these are candidates
  58. t2 = random.randint(0,3)
  59. while(t1==t2):
  60. t1 = random.randint(1, 3)
  61.  
  62. p1 = par[t1]
  63. p2= par[t2]
  64. print("Candidate parents",p1,p2)
  65.  
  66. #Crossover
  67. c1 = p1[0:3]+p2[3:]
  68. print("After Crossover:",c1)
  69. #Mutation
  70. child = [0,0,0,0,0,0]
  71. t2 = random.randint(0, 5)
  72. for j in range(0,6):
  73. child[j] = c1[j]
  74.  
  75. if child[t2] == '1':
  76. child[t2] = '0'
  77. else:
  78. child[t2] = '1'
  79.  
  80. c1 = ''.join(child)
  81. print("After Mutation:", c1)
  82. #Validation
  83. chWt1, chPt1 = fitScore(c1)
  84. if chWt1 <= 30:
  85. x = minAndBetter(chPt1)
  86. par[x] = c1
  87.  
  88. print(">>>>>",c1,"Weight",chWt1,"Point",chPt1)
  89.  
  90. # termination after 15 generation
  91. i+=1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement