Skip to content Skip to sidebar Skip to footer

Generating Random Number With Different Digits

So I need to write a program which generates random numbers from 100 to 999, and the tricky part is that the digits in the number can't be the same. For example: 222, 212 and so on

Solution 1:

It might be easier to use random.sample to sample from the distribution [0,9] without replacement, rejecting any samples which select 0 first:

import random

def pick_number():
    a = 0
    while a == 0:
        a, b, c = random.sample(range(10), 3)
    return 100*a + 10*b + c

Further explanation: range(10) (in Python 2) generates the list [0,1,2,3,4,5,6,7,8,9], and random.sample picks 3 elements from it without replacement. The while loop repeats until the first element, a is not zero, so when it exits you have the three digits of a number that meets the requirements. You can turn this into a single integer by multiplying the first by 100, the second by 10 and then adding all three.


Solution 2:

To loop until it's ok you can also use while in Python:

from random import randint

a = randint(1, 9)
b = randint(0, 9)
c = randint(0, 9)
while not (a!=b and b!=c and c!=a):
    a = randint(1, 9)
    b = randint(0, 9)
    c = randint(0, 9)

You can also put it in a function:

def generate_number():
    a = randint(1, 9)
    b = randint(0, 9)
    c = randint(0, 9)
    while not (a!=b and b!=c and c!=a):
        a = randint(1, 9)
        b = randint(0, 9)
        c = randint(0, 9)
    return (a, b, c)

And if you want n such numbers (they are not actually numbers since (a, b, c) is a tuple of 3 int values), you can call it n times:

for i in range(n):
    print(generate_number())

If you prefer formatting the values, you can also do:

for i in range(n):
    print('%d %d %d'%generate_number()) # old style formatting
    print('{} {} {}'.format(*generate_number())) # new style

Finally, you can use get n from the command line:

import sys
n = sys.argv[1]

Or you can ask it directly:

n = int(input("Please enter some number: ")) # in python2.x you'd use raw_input instead of input

You'll get an exception if the value cannot be converted; you can catch the exception and loop as for the generation of numbers.

Putting it all together with the typical main construct:

from random import randint
import sys

def generate_number():
    a = randint(1, 9)
    b = randint(0, 9)
    c = randint(0, 9)
    while not (a!=b and b!=c and c!=a):
        a = randint(1, 9)
        b = randint(0, 9)
        c = randint(0, 9)
    return (a, b, c)

def main():
    n = sys.argv[1]
    for i in range(n):
        print('{} {} {}'.format(*generate_number()))

if __name__=='__main__':
    main()

Solution 3:

Instead of generating 3 random numbers create a list of numbers 0-9 then call random.shuffle on it. You then just pull out as many digits as you need from the shuffled list and no digit will be repeated

import random

def generate_number():
    numbers = range(10) # Generates a list 0-9
    random.shuffle(numbers) # Shuffle the list

    return (numbers[0], numbers[1], numbers[2]) #take the first 3 items

(This answer is pretty much the same as xnx's answer execpt it uses the method shuffle which can be used in version prior to 2.3 and it does not loop waiting for a non 0 first digit.)


Solution 4:

On top of @xnx answer, some background: this is called Fisher-Yates (or F-Y-Knuth) shuffle, and it is similar to randomly picking lottery tickets, using ticket only once. O(n) complexity, more to read here http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle


Post a Comment for "Generating Random Number With Different Digits"