4

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?

4
  • 3
    Remove your random.seed() call. Commented Apr 13, 2018 at 8:28
  • do you have the same python version on your friend's computer ? Commented Apr 13, 2018 at 8:34
  • If you run it twice on the same computer of your friend, does it twice give the same result? Commented Apr 13, 2018 at 8:34
  • I tried it and it also always give me the same lists at every run, it is not computer dependent. As hinted above, it is due to the seeeding of the random number generator Commented Apr 13, 2018 at 8:36

2 Answers 2

6

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.)

Sign up to request clarification or add additional context in comments.

1 Comment

For such reason, one could feel tortured for no reaching the same results of Central Limit Theorem from this example, since the samples generated for a population, are different, from one machine to another: towardsdatascience.com/…
2

When you write

random.seed(1)

You are saying to always use the same sequence of randomly generated numbers, therefore you always have the same results. It happens when I run it on my computer too.

Simply remove the line and you should have different randomly generated numbers every time.

See this answer for an explanation of the seed.

And the python documentation for the random library

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.