Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
602 views
in Technique[技术] by (71.8m points)

python - Generate random numbers only with specific digits

How do I generate a random number from a specific set of digits? For example,
I want to generate numbers from the range 1-100,000 such that every number has only odd digits (for example: 111, 1351, 19711 etc..)

Using the random module I tried:

import random

rand = random.randint([1, 3, 5, 7, 9]) 

Is there any efficient way of doing it?
Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One way could be to define a list of odds from which to sample, but keeping in mind the how likely it should be for a number to be sampled randomly. Since there are ten times as many 2 digit numbers than 1 digit numbers, we need to set the weights of these sampling sizes according to this logic.

Following this reasoning, we could use numpy.random.choice, which allows for sampling from a list following a probability distribution:

from numpy.random import choice

odds = ['1','3','5','7','9']

n_digits = 5 # up to 99999 for ex
range_digits = list(range(1,n_digits))

weights = [5**i for i in range_digits]
weights_sum = sum(weights)
probs = [i/weights_sum for i in weights]

sizes = choice(range_digits,size=n,p=probs)
[int(''.join(choice(odds,size))) for size in sizes]
# [3151, 3333, 1117, 7577, 1955, 1793, 5713, 1595, 5195, 935]

Let's check the generated distribution for 10_000 samples:

from collections import Counter

sizes = choice(range_digits,size=10_000,p=probs)
out = [int(''.join(choice(odds,size))) for size in sizes]

Counter(len(str(i)) for i in out)
# Counter({4: 8099, 3: 1534, 2: 304, 1: 63})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...