題目如下:
用 Rand7() 實現(xiàn) Rand10()
首先需要注意的是,數(shù)字1-10應(yīng)該具有相同的生成概率喳整。由于我們只能使用rand7函數(shù)尔苦,所以思路必然是組合使用rand7函數(shù)署惯。
如果假設(shè):
a = rand7()
b = rand7()
那么通過 x = a + (b - 1) * 7
可以獲取數(shù)字 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.]]
對于數(shù)字x: 1---40,我們可以通過 (x - 1) % 10 + 1
來均等的生成1到10 的整數(shù):
[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]
可以看到延刘,每個數(shù)都出現(xiàn)了4次漫试。對于41 --- 49,比較簡單的處理方式是直接拋棄访娶。 直到獲取的數(shù)字是1到40為止商虐。 每次運行程序會生成1到40的概率p為: 40/49
, 根據(jù)獨立事件的期望公式Ex = np
, 程序運行的期望運行次數(shù)為n為 1.225觉阅,每次運行會調(diào)用2次rand7函數(shù),所以rand7函數(shù)的調(diào)用次數(shù)期望為 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版 持續(xù)更新)]
(http://www.reibang.com/p/60b5241ca28e)
ps:如果您有好的建議典勇,歡迎交流 :-D,
也歡迎訪問我的個人博客 苔原帶 (www.tundrazone.com)