如何在python中使用random.randint更新变量?
我有一些GA的代码,它是这样开始的如何在python中使用random.randint更新变量?,python,global-variables,genetic,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(
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 = []
重要的部分是打印POP\u大小
它打印需要的内容,然后POP_大小保持不变,但是随机的
只有当我退出程序并重新启动它时
我希望它在我开始设置的参数之间有所不同,这是
POP_SIZE = random.randint(100,200)
想法?您可以打印POP\u SIZE()
而不是打印POP\u SIZE
,其中:
def POP_SIZE():
return random.randint(100,200)
每次调用POP_SIZE()
时,它都会返回一个新的随机整数
for generation in xrange(GENERATIONS):
...
print POP_SIZE()
...
您可以打印POP\u SIZE()
而不是打印POP\u SIZE
,其中:
def POP_SIZE():
return random.randint(100,200)
每次调用POP_SIZE()
时,它都会返回一个新的随机整数
for generation in xrange(GENERATIONS):
...
print POP_SIZE()
...
把它移到for循环中?现在,您正在生成一个随机数…POP_大小是否需要在循环中才能每次重新计算?我遗漏了什么吗?回答一下,@David。把它移到for循环中?现在,您正在生成一个随机数…POP_大小是否需要在循环中才能每次重新计算?我是不是遗漏了什么?回答一下,大卫。哼。。。当我尝试这样做时,它只是说“对于xrange中的I(POP_SIZE):TypeError:需要一个整数”是的,但我不想返回并用POP_SIZE()替换POP_SIZE。。。所以我重写了它,就像导入随机变量、全局变量、设置最优字符串和GA输入变量一样OPTIMAL=“我的名字是billy bob,我喜欢奶酪”DNA_SIZE=len(OPTIMAL)def random_function():return random.randomint(100200)POP_SIZE=random_function()GENERATIONS=200,现在我得到了这个错误”第11行,在random_function return random.randomint(100200)中AttributeError:'模块'对象没有属性'randomint''抱歉,我不知道如何格式化代码。。。请不要投反对票,我正试图弄清楚这一切。最后一个错误是因为你用错了名字。它是randint
而不是randomint
。无论如何,如果您不想使用某个函数,那么您只能使用一个随机数。@user1742566您应该添加您的解决方案作为答案:)哼哼。。。当我尝试这样做时,它只是说“对于xrange中的I(POP_SIZE):TypeError:需要一个整数”是的,但我不想返回并用POP_SIZE()替换POP_SIZE。。。所以我重写了它,就像导入随机变量、全局变量、设置最优字符串和GA输入变量一样OPTIMAL=“我的名字是billy bob,我喜欢奶酪”DNA_SIZE=len(OPTIMAL)def random_function():return random.randomint(100200)POP_SIZE=random_function()GENERATIONS=200,现在我得到了这个错误”第11行,在random_function return random.randomint(100200)中AttributeError:'模块'对象没有属性'randomint''抱歉,我不知道如何格式化代码。。。请不要投反对票,我正试图弄清楚这一切。最后一个错误是因为你用错了名字。它是randint
而不是randomint
。无论如何,如果您不想使用某个函数,那么您只能使用一个随机数。@user1742566您应该添加您的解决方案作为答案:)