Random Number 1 to 7 With Equal Probability

Given a function rand5() which generated random numbers from 0 to 5. Use this function to create rand7(). In deep approach was asked and further discussion was made regarding how to generalize it for creating m random number generator from n random number generator. Plz give solution with proper explanation.

Analysis

链接:https://www.nowcoder.com/questionTerminal/a475db9aa74747709e65399c0c7d86d2

来源:牛客网

可推广至更加一般的情况,对于利用可以产生1~N的随机数ranN(),生成1~M的随机数,只需要满足

MAX((randN()-1) * N + (randN()-1)) >= M都可以使用以上述方法类似的方法实现。

令 n = N-1 (randN()-1) * N + (randN()-1) 将以等概率生成N进制数 0 ~nn (换成十进制为 (N-1)*10 + (N-1))。 为了让新生成的随机数等概率, 只取前0 ~ (M*k-1) 个数(M*k-1<nn均可) 余M + 1

求得 randM()随机数

Reference:

Solution

# Author:流月0
# Link:https://www.jianshu.com/p/71d816fae2e4

import random


# 原有生成1-5随机数的函数
def random_5():
    return random.randint(1, 5)


# 要获得的生成1~7随机数的函数
def random_7():
    while True:  # 避免没有返回值
        n = (random_5()-1)*5 + random_5()-1  # 生成0~24的随机数
        if n <= 20:
            return n % 7 + 1


if __name__ == '__main__':
    print(random_7())

Last updated