@@ -367,7 +367,8 @@ def genetic_algorithm(population, fitness_fn, ngen=1000, pmut=0.1):
367
367
for i in range (ngen ):
368
368
new_population = []
369
369
for i in len (population ):
370
- p1 , p2 = random_weighted_selections (population , 2 , fitness_fn )
370
+ fitnesses = map (fitness_fn , population )
371
+ p1 , p2 = weighted_sample_with_replacement (population , fitnesses , 2 )
371
372
child = p1 .mate (p2 )
372
373
if random .uniform (0 , 1 ) < pmut :
373
374
child .mutate ()
@@ -389,25 +390,6 @@ def mutate(self):
389
390
"Change a few of my genes."
390
391
abstract
391
392
392
- def random_weighted_selection (seq , n , weight_fn ):
393
- """Pick n elements of seq, weighted according to weight_fn.
394
- That is, apply weight_fn to each element of seq, add up the total.
395
- Then choose an element e with probability weight[e]/total.
396
- Repeat n times, with replacement. """
397
- totals = []; runningtotal = 0
398
- for item in seq :
399
- runningtotal += weight_fn (item )
400
- totals .append (runningtotal )
401
- selections = []
402
- for s in range (n ):
403
- r = random .uniform (0 , totals [- 1 ])
404
- for i in range (len (seq )):
405
- if totals [i ] > r :
406
- selections .append (seq [i ])
407
- break
408
- return selections
409
-
410
-
411
393
#_____________________________________________________________________________
412
394
# The remainder of this file implements examples for the search algorithms.
413
395
@@ -885,7 +867,4 @@ def compare_graph_searchers():
885
867
886
868
>>> boggle_hill_climbing(list('ABCDEFGHI'), verbose=False)
887
869
(['E', 'P', 'R', 'D', 'O', 'A', 'G', 'S', 'T'], 123)
888
-
889
- >>> random_weighted_selection(range(10), 3, lambda x: x * x)
890
- [8, 9, 6]
891
870
""" )
0 commit comments