如何在python中使用random.randint更新变量?

时间:2012-10-12 23:44:04

标签: python global-variables genetic

我有一些GA的代码,就像这样开始

import random

#
# Global variables
# Setup optimal string and GA input variables.


POP_SIZE    = random.randint(100,200) 

# random code that doesn't really matter...

# Simulate all of the generations.
  for generation in xrange(GENERATIONS):
    print "Generation %s... Random sample: '%s'" % (generation, population[0])
    print POP_SIZE 
    weighted_population = []

重要的部分是print POP_SIZE

它打印它需要的内容,然后POP_SIZE保持不变,但随机化 只有当我退出程序并重新启动它时。

我希望它在我在开头设置的参数之间变化,这是

POP_SIZE    = random.randint(100,200)

思想?

1 个答案:

答案 0 :(得分:0)

而不是print POP_SIZE,您可以print POP_SIZE()在哪里:

def POP_SIZE():
    return random.randint(100,200)

每次拨打POP_SIZE()时,都会返回一个新的随机整数。

for generation in xrange(GENERATIONS):
    ...
    print POP_SIZE()
    ...