Search code examples
pythonpython-3.xcode-testing

Why are the values in my random list are always the same?


This code is for a maximum pairwise product, I've been testing it but I have come across some issues.

import sys
import random
while True:
    a=int(random.randrange(1,1000000,101))
    keys =[]     # keys is empety list
    i=0

    while i < a :
        keys.append(int(random.randrange(1,10000,8)))
        i=i+1

    keys.sort()
    print(keys[-1], keys[-2])
    x=keys[-1]*keys[-2]
    print( "the max is ",x)

However, for some reason, the output of the code is always the same.

9993 9993
the max is  99860049
9993 9993
the max is  99860049
9993 9993
the max is  99860049
9993 9993
the max is  99860049

I don't understand why this is happening, an explanation would be appreciated.


Solution

  • This is happening because you are sorting your list, so that the largest numbers are at the end. The list keys is going to contain hundreds of thousands of numbers, and as there are only 1249 possible keys (9993 - 1) / 8 = 1249 you are incredibly likely to get two instances of the largest possible number, 9993. However, this isn't always the case, when I ran your code one time I got a different result:

    9993 9993
    the max is  99860049
    9993 9993
    the max is  99860049
    9977 9969 #<-- Not 9993
    the max is  99460713
    9993 9993
    the max is  99860049
    

    This demonstrates how it is purely down to chance, I hope this helped!