Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Python random is generating the same numbers?

I wrote this code for my homework:

import random
score=[]
random.seed(1)
for i in range(0,100):
    score.append(random.randrange(0,21))

for k in range(20, -1, -1):
    print("Who get %2d score in test? : "%(k), end='')
    while score.count(k)!=0:
        j = score.index(k)
        print("%3s" % (j), end="  ")
        score.remove(k)
        score.insert(j,25)
    print("\n")

I ran it on my computer many times and the results were the same. Ironically, in other computers, the results are different from my computer, but also also getting repeated at each execution.

What's wrong with my code?

like image 650
dawin Avatar asked Oct 30 '25 08:10

dawin


1 Answers

random.seed(n) starts the random number generator off from the same point each time the program is run.

That is you get the same sequence of random numbers. It is like taking a video of a dice being thrown and then playing it back each time - the numbers are random (pseudo random to be accurate) but you are playing back the sequence.

This is useful for testing, for example: you can run different versions of your program with the same random numbers, so you are sure differences in your results are only due to the program, not to chance.

Take random.seed out and you will get a sequence that starts at a random location. (On most computers, if you don't specify a seed, the clock time the program started is implicitely used as seed.)

like image 199
Mike James Avatar answered Nov 01 '25 21:11

Mike James