-1

i'm looping through an array and changing its item by a random number between 1 and 10

from time import sleep as wait
from os import system as sys
import random
memory = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]

def cls(): sys("cls")

def main():
    for i in memory:
        memory[i] = random.randrange(1,10)
        print(memory)
        wait(0.1)
        cls()
    print("OK")
    input("")

if __name__ == '__main__':
    main()

but it only changes the first item of the array

how can i fix this?

legend
  • 41
  • 5
  • 1
    You are using the _values_ of `memory`, so you are repeatedly changing `memory[0]`, as many time as you have `0` in the array. Voting to close as typo. – tripleee Oct 02 '22 at 17:53
  • As an aside, the wait and clearing the screen at the end are horrible ideas. – tripleee Oct 02 '22 at 17:56

4 Answers4

0

change your for loop :

for i in range(len(memory)):

in your for each loop i always 0 and you refers to first element ..

0

Because your i is always 0. And you change only the first element.
I also replaced your class method, by print() parameters.
Please try this snippet:

from time import sleep as wait
import random

memory = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]


def main():
    for i, item in enumerate(memory):
        item = random.randrange(1,10)
        memory[i] = item
        print(memory, end="\r", flush=True)
        wait(0.1)
    print("OK")
    input("")

if __name__ == '__main__':
    main()
JacekK
  • 623
  • 6
  • 11
0

I am not sure if this is effecient for your case. but it can achieve the output you want.

from time import sleep as wait
from os import system as sys
import random

memory = [0 for _ in range(0, 29)]

def cls(): sys("cls")

def main():
    global memory
    for _ in memory:        
        ran_index = random.randrange(1, 29)
        memory[ran_index] = random.randrange(1,10)
        print(memory)
        memory = [0 for _ in range(0, 29)]
        wait(0.1)
        cls()
    print("OK")
    input("")

if __name__ == '__main__':
    main()
0

Your loop:

for i in memory:

Has i represent each element of the array in turn. All of those elements are 0.

Thus:

memory[i] = random.randrange(1,10)

Only ever assigns to the first element in memory.

To iterate over the indices of memory:

for i in range(len(memory)):

But really, if you just want 29 random numbers on a list, a list comprehension will do that jobh much more cleanly.

memory = [random.randrange(1,10) for _ in range(29)]
Chris
  • 26,361
  • 5
  • 21
  • 42