【问题标题】:for loop creates a dictionary with x entries but after the loop, length of dictionary is < xfor 循环创建一个包含 x 个条目的字典,但在循环之后,字典的长度为 < x
【发布时间】:2019-06-16 10:55:10
【问题描述】:

所以,我正在 Python 中实现 TSP 的遗传算法。为了计算下一代,我实现了这个函数:

def nextGen(currPop, distDict, numChrome, mutRate):

     genFit = {}

     for i in currPop:
         tmp = fitness(i, distDict)
         genFit[tuple(i)] = tmp
         print(tmp)

     genFitCum = dictCum(genFit)

     print(len(genFit), len(currPop))

     parentSelection = parents(genFitCum, numChrome)

     children = breedPopulation(parentSelection, numChrome)

     nextGeneration = mutatePop(children, mutRate)

     return nextGeneration

distDict 是各个城市之间距离的字典。 numChrome 是染色体数。 mutRate 是突变率。

现在,在第一代之后,我得到了不应该存在的越界错误,因为它都在循环中。

问题是 currPop 的长度是恒定的(numChrome),但 genFit 的长度会减少。这是在循环运行 numChrome 次之后。

我想我的实现可能会占用磁盘空间。我尝试使用del,但没有成功。

【问题讨论】:

  • 您需要提供minimal reproducible example。无论如何,我怀疑您的密钥不是唯一的。 currentPop 中有什么内容?
  • 如果你的字典的长度是
  • 我严重怀疑这是内存问题。
  • 你们是对的。我的钥匙不是唯一的。正要删除问题。关于如何保持它们的独特性有什么建议吗? PS:很抱歉没有维护网站的代码。下次会注意的。

标签: python python-3.x genetic-algorithm


【解决方案1】:

在为其分配值之前检查您的密钥是否已经存在。

# Not sure if str(tuple(i)) will work - regardless apply logic like this to make the Key unique
counter = 0
while((str(tuple(i)) + '_' + str(counter)) in genFit.keys()):
  counter += 1
genFit[str(tuple(i) + '_' + str(counter)] = tmp

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-17
    • 1970-01-01
    • 1970-01-01
    • 2023-01-17
    • 2016-01-11
    相关资源
    最近更新 更多