fuzzyhedge - 1 year ago 75

Python Question

This is a simple evolutionary algorithm. Each iteration of the loop randomly permutes the initial conditions of a function, and updates the initial conditions for the next iteration with the best solution found thus far.

To avoid falling into local optimal cycles, I would like the algorithm to reject solutions that are equal to any 3 previous (or n previous) solutions.

How do I create such a list?

`for j in range(0, its+1):`

# Seed initial conditions with best condition thus far.

k2, candidate1, candidate2 = k1, best_cond1, best_cond2

# Choose random nodes to swap from current conditions.

rand_node1, rand_node2 = choice(best_cond1), choice(best_cond2)

# Swap the nodes to create new candidate lists.

candidate_list1.append(rand_node2).remove(rand_node1)

candidate_list2.append(rand_node1).remove(rand_node2)

# Calculates a solution given the new conditions.

k2 = cost(candidate_list1, candidate_list2)

if k2 < k1:

k1, best1, best2 = k2, candidate1, candidate2

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

You can do something like this:

```
last_three = []
for j in range(1, its + 2):
...
k2 = cost(candidate1, candidate2)
if k2 in last_three:
continue
elif k2 < k1:
...
last_three[(j%3)-1] = k2
```

I had to change the loop to start at `1`

in order to do the `j%3`

thing.

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**