1
+ """Implementation of Coin change problem using Genetic Algorithm."""
2
+
1
3
import numpy as np
2
4
import pandas as pd
3
5
4
6
5
7
class Chromosome :
8
+ """Class to manage individual chromosomes in genetic algorithm.
9
+ """
6
10
7
11
def __init__ (self , size , N , denominations ) -> None :
8
12
self .N = N
@@ -14,14 +18,14 @@ def __init__(self, size, N, denominations) -> None:
14
18
def fitness (self ):
15
19
return 1 / (1 + np .abs (np .sum (self .genes * self .denominations ) - self .N ))
16
20
17
- def __lt__ (self , __o : object ) -> bool :
18
- return self .fitness > __o .fitness
21
+ def __lt__ (self , o : object ) -> bool :
22
+ return self .fitness > o .fitness
19
23
20
- def __eq__ (self , __o : object ) -> bool :
21
- return self .fitness == __o .fitness
24
+ def __eq__ (self , o : object ) -> bool :
25
+ return self .fitness == o .fitness
22
26
23
- def __gt__ (self , __o : object ) -> bool :
24
- return self .fitness < __o .fitness
27
+ def __gt__ (self , o : object ) -> bool :
28
+ return self .fitness < o .fitness
25
29
26
30
def single_point_crossover (self , chromosome ):
27
31
crossover_point = np .random .randint (1 , self .size - 1 )
@@ -40,6 +44,8 @@ def mutate(self, mutation_probability):
40
44
41
45
42
46
class GeneticAlgorithm :
47
+ """Class to manage genetic algorithm for 0/1 Knapsack problem.
48
+ """
43
49
44
50
def __init__ (self ,
45
51
population_size ,
@@ -85,10 +91,9 @@ def evolve(self, log_freq=1000):
85
91
generations = 0
86
92
while self .fittest_chromosome ().fitness < 1 :
87
93
ga .next_generation ()
88
- if generations % 100 == 0 :
89
- print (
90
- f'Generation { generations } : Max fitness = { self .fittest_chromosome ().fitness } '
91
- )
94
+ if generations % log_freq == 0 :
95
+ max_fitness = self .fittest_chromosome ().fitness
96
+ print (f'Generation { generations } : Max fitness = { max_fitness } ' )
92
97
generations += 1
93
98
return self .fittest_chromosome ()
94
99
@@ -105,4 +110,4 @@ def evolve(self, log_freq=1000):
105
110
soln_table = pd .DataFrame (columns = ['Denominations' , 'Count' ])
106
111
soln_table ['Denominations' ] = denominations
107
112
soln_table ['Count' ] = solution .genes
108
- print (soln_table .to_string (index = False ))
113
+ print (soln_table .to_string (index = False ))
0 commit comments