470. leetcode題目講解(Python):用 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)

ps:如果您有好的建議,歡迎交流 :-D,
也歡迎訪問我的個人博客 苔原帶 (www.tundrazone.com)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章