random number

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Mar 26 03:24:38 EDT 2012


On Mon, 26 Mar 2012 08:40:00 +0200, Michael Poeltl wrote:

> * Nikhil Verma <varma.nikhil22 at gmail.com> [2012-03-26 08:09]:
>> Hi All
>> 
>> How can we generate a 6 digit random number from a given number ?
> what about this?
> 
>>>> given_number=123456
>>>> def rand_given_number(x):
> ...     s = list(str(x))
> ...     random.shuffle(s)
> ...     return int(''.join(s))
> ...
>>>> print (rand_given_number(given_number))
> 653421


That's not very random. In fact, it is *terrible* as a random number 
generator.

A truly random six digit number will include any number between 100000 
through 999999. There are exactly 900000 (nine hundred thousand) such 
numbers.

The way you generate the not-quite-random numbers, you miss out on almost 
all of them. E.g. you can generate 123456 but not 123455 or 123457.

In total, you generate only 6! = 6*5*4*3*2*1 = 720 numbers, no matter how 
many millions of times you call the function. Here is a demonstration:

>>> given = 123456
>>> def rand_num(x):
...     s = list(str(x))
...     random.shuffle(s)
...     return int(''.join(s))
... 
>>> import random
>>> results = set()
>>> for i in range(10**7):
...     results.add(rand_num(given))
... 
>>> len(results)
720

So slightly more than 99% of all the six digit numbers will never be 
generated using your method.



-- 
Steven



More information about the Python-list mailing list