【发布时间】:2014-05-14 22:44:04
【问题描述】:
应该发生什么:
使用包含随机整数的属性创建一个随机对象群体,所有对象都将以 10 的再现机会开始。(第 16 行)
对于所有“数字”属性大于 4 的对象,将 10 添加到与该对象相关的 chance_of_rep 属性。(第 21 行)
根据“chance_of_rep”属性,决定是否繁殖后代。 (第 36 行)
每一代,将每个成员的年龄加1,如果年龄大于1,则杀死该成员。(第47行)
真正发生的事情:
“chance_of_rep”属性将在 50 处结束,并且不会高于此值。为什么是这样? 除此之外,其他一切都按其应有的方式工作(至少我相信如此,请提及任何看起来有问题的地方)。
import random as r
import os
import sys
import time
from subprocess import call
#call('color a', shell=True)
class Entity(object):
def __init__(self, number):
self.number = number
self.chance = 10
self.age = 0
class Fitness(object):
def __init__(self, population):
self.population = population
def StartPopulation(self, pop, entities):
for x in range(pop):
entity = Entity(r.randint(3, 5))
entities.append(entity)
def FitnessMethod(self, entities):
for x in entities:
if x.number >= 5:
x.chance += 10
else:
x.chance += 0
if x.chance > 100:
x.chance = 100
else:
x.chance += 0
def Reproduce(self,entities):
for x in entities:
if r.randint(0, 100) < x.chance:
random_children = r.randint(1, 3)
for a in range(random_children):
entity = Entity(x.number)
entity.chance = x.chance
entities.append(entity)
x.age += 1
def Aging(self, entities):
for x in entities:
if x.age >= 2:
entities.remove(x)
pop = r.randint(3, 5)
entities = []
Fitness = Fitness(pop)
Fitness.StartPopulation(pop, entities)
for x in entities:
print x.number, x.chance
print "~~~~~~~~~~~~~\n"
raw_input()
for x in range(30):
Fitness.FitnessMethod(entities)
Fitness.Reproduce(entities)
Fitness.Aging(entities)
for x in entities:
print x.number, x.age, x.chance
print "Generation_Mutation_Complete"
raw_input()
顺便说一句,这不是家庭作业,这是个人项目。
【问题讨论】:
-
要求人们发现代码中的错误并不是特别有效。您应该使用调试器(或添加打印语句)来隔离问题,方法是跟踪程序的进度,并将其与您期望发生的情况进行比较。一旦两者发生分歧,那么您就发现了您的问题。 (然后如果有必要,你应该构造一个minimal test-case。)
-
哇,有点苛刻,毕竟这是一个问答网站。
-
是编程知识问答,不是众包调试器...
-
来吧,真的吗?你连尝试和帮助都不打算?
标签: python-2.7 evolutionary-algorithm