2016-12-14 69 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]]