用 Rand7() 实现 Rand10()

首先需要注意的是,数字1-10应该具有相同的生成概率。由于我们只能使用rand7函数,所以思路必然是组合使用rand7函数。

如果假设:

a = rand7()
b = rand7()

那么通过 x = a + (b - 1) * 7 可以获取数字 1 到 49:

[[ 1.  8. 15. 22. 29. 36. 43.]
 [ 2.  9. 16. 23. 30. 37. 44.]
 [ 3. 10. 17. 24. 31. 38. 45.]
 [ 4. 11. 18. 25. 32. 39. 46.]
 [ 5. 12. 19. 26. 33. 40. 47.]
 [ 6. 13. 20. 27. 34. 41. 48.]
 [ 7. 14. 21. 28. 35. 42. 49.]]

对于数字x: 1---40,我们可以通过 (x - 1) % 10 + 1 来均等的生成1到10 的整数:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 
1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

可以看到,每个数都出现了4次。对于41 --- 49,比较简单的处理方式是直接抛弃。 直到获取的数字是1到40为止。 每次运行程序会生成1到40的概率p为: 40/49, 根据独立事件的期望公式Ex = np, 程序运行的期望运行次数为n为 1.225,每次运行会调用2次rand7函数,所以rand7函数的调用次数期望为 2.45。

参考代码如下:

# Created by Jedi.L
# The rand7() API is already defined for you.
# def rand7():
# @return a random integer in the range 1 to 7

class Solution:
    def rand10(self):
        """
        :rtype: int
        """
        idx = 49
        while idx > 40:
            row = rand7()
            col = rand7()
            idx = row + (col - 1) * 7
            if idx <= 40:
                return 1 + (idx - 1) % 10

源码地址:
https://github.com/jediL/LeetCodeByPython

其它题目:[leetcode题目答案讲解汇总(Python版 持续更新)]
(https://www.jianshu.com/p/60b5241ca28e)

关注公众号 海量干货等你
原文地址:https://www.cnblogs.com/sowhat1412/p/12734281.html