leetcode 470. Implement Rand10() Using Rand7() (python)

516 阅读1分钟

描述

Given the API rand7() that generates a uniform random integer in the range [1, 7], write a function rand10() that generates a uniform random integer in the range [1, 10]. You can only call the API rand7(), and you shouldn't call any other API. Please do not use a language's built-in random API.

Each test case will have one internal argument n, the number of times that your implemented function rand10() will be called while testing. Note that this is not an argument passed to rand10().

Example 1:

Input: n = 1
Output: [2]	

Example 2:

Input: n = 2
Output: [2,8]

Example 3:

Input: n = 3
Output: [3,8,10]

Note:

What is the expected value for the number of calls to rand7() function?
Could you minimize the number of calls to rand7()?

解析

暂无

解答

class Solution(object):
    def rand10(self):
        return self.rand40() % 10 + 1
        
    def rand49(self):
        return 7 * (rand7() - 1) + rand7() - 1
        
    def rand40(self):
        num = self.rand49()
        while num >= 40:
            num = self.rand49()
        return num
        	      
		

运行结果

Runtime: 444 ms, faster than 35.64% of Python online submissions for Implement Rand10() Using Rand7().
Memory Usage: 18.7 MB, less than 23.76% of Python online submissions for Implement Rand10() Using Rand7().

原题链接:leetcode.com/problems/im…

您的支持是我最大的动力