2016-12-14 72 views
0
from pylab import * 
import numpy as np 
import sys 
def initial(): 
    generation = [0,0,1,1,1,1,1,1,1,0,0,0,0,0] 
    generation = generation 
    return generation 
def fitness(flag): 
    global transfer 
    transfer = [] 
    newgeneration1 = pairing() 
    scores = [1,2,3,7,6,5,3] 
    if flag < 1: 
     generation = initial() 
    else: 
     generation = newgeneration1 
    transfer.append(generation) 
    transfer.append(scores) 
    print(transfer) 
    return transfer 
def pairing(): 
    transfer = fitness(i) 
    scores = transfer[1] 
    generation1 = transfer[0] 
    newgeneration = [1,0,1,0,0,0,0,0,1,0,1,1,1,1] 
    return newgeneration 

initial() 
for i in range(3): 
    fitness(i) 
    pairing() 
    if i == 3: 
     scores = fitness(i) 
     print("The following is the final generation: ") 
     print(pairing(i-1)) 
     print("Here are the scores: ") 
     print(scores) 
     sys.exit() 

以上是我在python 3.5中的遗传算法代码的一个简化版本,当我运行这个时我收到一个错误,说:超过最大递归深度,I我试图让它做一次初始函数,然后在适应度和配对之间循环一定次数的迭代,问题是,配对()创建新一代,并且健身需要采用新一代并确定其适应度,然后它发送到配对,另一个新一代创建..等等。你明白了。预先感谢任何帮助!Python 3.5 - 遗传算法循环

+0

'配对()'叫'健身(我)'和'健身()'叫'配对()'没有任何有条件的判断。这是一个死循环。 –

+0

并避免使用'global'。相反,将'transfer'传递给'paring' – pylang

+0

如果你正在尝试做可再现的工作,不要从'''pylab import *'执行''。这会摧毁你的名字空间。 – pylang

回答

0

这里的问题:

所以,让我们通过你的程序走...

  • 首先调用initial()
  • 接下来你叫fitness(i)
  • 你叫paringfitness函数内在01240702892845267539里面函数调用fitness
  • 你叫paring ....

什么,你在这里得到的是一个无限循环,因为fitnessparing保持通话对方

这里的fitness函数内解决方案:

def pairing(): 
    global transfer # transfer is a global variable, you don't need to call a function to get it 
    #transfer = fitness(i) 
    #scores = transfer[1] # you've already defined these variables, no need to define them again 
    #generation1 = transfer[0] 
    newgeneration = [1,0,1,0,0,0,0,0,1,0,1,1,1,1] 
    return newgeneration 

我已经取出了一些不必要的锂从您的配对功能NES,程序现在工作,因为它应该

下面是输出:

[[0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0], [1, 2, 3, 7, 6, 5, 3]] 
[[1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1], [1, 2, 3, 7, 6, 5, 3]] 
[[1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1], [1, 2, 3, 7, 6, 5, 3]]