2

I'm having this problem in python where I can't generate different random numbers in a loop. Every loop generates same numbers. My code looks like this:

import random

class Dna :
    genes = []

    def __init__(self, lifespan) :

        sum = 0
        for i in range(lifespan) :
            self.genes.append(PVector(random.randrange(-10, 10), random.randrange(-10, 10)))
            sum += self.genes[i].mag()

        print(sum)

Here, I'm trying to generate random vectors in the range -10 and 10 but every different DNA object prints the same sum. Here is the main file:

import dna

def setup() :

    d = dna.Dna(200)
    d2 = dna.Dna(200)

And I'm using processing.py for this.

7
  • You're missing some vitally important code in your question. Commented Feb 28, 2018 at 10:53
  • 1
    Which one? If you're talking about that 'population' line, you can ignore that Commented Feb 28, 2018 at 10:55
  • 1
    @MosteM Thanks for the suggestion but I don't need to generate same streams of random numbers. Commented Feb 28, 2018 at 11:02
  • 1
    @ibt23sec5 It's processing's built-in object for 2D and 3D Vectors Commented Feb 28, 2018 at 11:02
  • 2
    If you want to diagnose such things in future, try doing print(self.genes) at the start and end of the constructor, and watch it grow. Commented Feb 28, 2018 at 11:12

1 Answer 1

6

genes needs to be an instance variable (one copy per instance of Dna class), not a class variable (one copy for the Dna class, shared by all instances).

def __init__(self, lifespan):
    self.genes = []
Sign up to request clarification or add additional context in comments.

1 Comment

Oh thanks man. I guess I'm missing some knowledge about classes in Python. :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.