0

I'm trying to learn some python and ran into some trouble with the random function combined with a for loop. The full code to run:

global_n = 3
import random
class InputNeuron:

    connections = list(range(global_n))
    connection_state = list(range(global_n))

    def __init__(self, n):
        self.n = n

my_inputs = list(range(global_n))

for i in range(0,global_n):
    my_inputs[i] = InputNeuron(global_n)

for i in range(0,3):
    for j in range(0,3):
        my_inputs[i].connections[j] = random.uniform(-1.0,1.0)
        my_inputs[i].connection_state[j] = random.uniform(-1.0,1.0)

for i in range(0, global_n):
    for j in range (0,global_n):
        print("Neuron", i, "connection", j, "is", my_inputs[i].connections[j], "and", my_inputs[i].connection_state[j])

I realise this code has many flaws, what I however cannot seem to grasp is why my random function is not working correctly. Specifically, as can be seen in the output when you run this, each "neuron" has the same output for the respective "connections" 0, 1 and 2. As far as I can tell this part of my code:

for i in range(0,3):
    for j in range(0,3):
        my_inputs[i].connections[j] = random.uniform(-1.0,1.0)
        my_inputs[i].connection_state[j] = random.uniform(-1.0,1.0)

Should assign random values to each of these values so that neuron 0, connection 0 and neuron 1, connection 0 should have different values.

I'm probably overlooking something obvious so apologies in advance, but after trying for literally hours now to fix this I'm very close to giving up on trying to figure out what is wrong.

Milan
  • 205
  • 2
  • 9
  • 3
    you're using class members, use instance members: `self.connections = ...` in the `__init__` method – Jean-François Fabre Jul 02 '18 at 14:26
  • 1
    @Jean-FrançoisFabre I'm sure you're right, but I can't figure out what you mean. Do you perhaps have a link to where this class members/instance members difference is explained for someone that doesn't seem to have a clue how it works? :) Edit: Well, you helped me somehow! I pasted the connections part inside the init def, now it seems to work. Thanks. – Milan Jul 02 '18 at 14:42

0 Answers0