【问题标题】:Create a list containing the results of n previous iterations of a loop创建一个包含循环前 n 次迭代结果的列表
【发布时间】:2016-11-25 05:13:17
【问题描述】:

这是一个简单的进化算法。循环的每次迭代都会随机置换函数的初始条件,并使用目前找到的最佳解来更新下一次迭代的初始条件。

为避免陷入局部最优循环,我希望算法拒绝等于任何 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

【问题讨论】:

  • 您应该修复代码中的缩进。
  • 已修复。对此感到抱歉。

标签: python list for-loop optimization


【解决方案1】:

你可以这样做:

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

我必须将循环更改为从1 开始才能执行j%3 的操作。

【讨论】:

  • 谢谢。像这样的东西应该工作。欣赏洞察力。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-22
  • 1970-01-01
  • 1970-01-01
  • 2015-11-26
  • 2023-03-07
  • 2015-09-20
相关资源
最近更新 更多