1

I have some code for a GA, that starts like this

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 = []

The important part is print POP_SIZE.

It prints what it needs to, and then the POP_SIZE stays the same, but is randomized ONLY if I exit the program and start it up again.

I want it to vary betweeen the paramaters I set at the beginning, which was

POP_SIZE    = random.randint(100,200)

Thoughts?

Adi Lester
  • 24,731
  • 12
  • 95
  • 110
Nathvi
  • 196
  • 1
  • 6
  • 14

1 Answers1

1

Rather than print POP_SIZE, you could print POP_SIZE() where:

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

Each time you call POP_SIZE() it will return a new random integer.

for generation in xrange(GENERATIONS):
    ...
    print POP_SIZE()
    ...
Andy Hayden
  • 359,921
  • 101
  • 625
  • 535
  • humm... when I try that it just says " for i in xrange(POP_SIZE): TypeError: an integer is required" – Nathvi Oct 12 '12 at 23:59
  • yeah, but I don't want to go back and replace POP_SIZE with POP_SIZE() everywhere... so i rewrote it like this import random # # Global variables # Setup optimal string and GA input variables. # OPTIMAL = "My name is billy bob and i like cheese" DNA_SIZE = len(OPTIMAL) def random_function(): return random.randomint(100,200) POP_SIZE = random_function() GENERATIONS = 200 and now im getting this error "line 11, in random_function return random.randomint(100,200) AttributeError: 'module' object has no attribute 'randomint'" – Nathvi Oct 13 '12 at 00:19
  • Sorry, i dont know how to format the code... please don't down vote this, im trying to figure all this out. – Nathvi Oct 13 '12 at 00:20
  • The last error you get is because you used the wrong name. It's `randint` not `randomint`. Anyway if you don't want to use a function than you are stuck with a single random number. – Bakuriu Oct 13 '12 at 08:03
  • @user1742566 you should add your solution as an answer :) – Andy Hayden Oct 13 '12 at 09:34
  • @user1742566 that's because you are trying to pass a function (?) into xrange (and it requires an integer). – Andy Hayden Oct 14 '12 at 20:00