创建一个列表,其中包含循环的n个先前迭代的结果

2024-10-01 00:21:29 发布

您现在位置:Python中文网/ 问答频道 /正文

这是一个简单的进化算法。循环的每次迭代都随机地排列函数的初始条件,并用迄今为止找到的最佳解更新下一次迭代的初始条件。你知道吗

为了避免陷入局部最优循环,我希望算法拒绝等于任何3个先前(或n个先前)解的解。你知道吗

如何创建这样的列表?你知道吗

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

Tags: to算法k2k1candidateconditionsbestnodes
1条回答
网友
1楼 · 发布于 2024-10-01 00:21:29

你可以这样做:

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

为了做j%3的事情,我不得不将循环改为从1开始。你知道吗

相关问题 更多 >