拒绝采样

470. 用 Rand7() 实现 Rand10()

难度中等

已有方法 rand7 可生成 1 到 7 范围内的均匀随机整数,试写一个方法 rand10 生成 1 到 10 范围内的均匀随机整数。

不要使用系统的 Math.random() 方法。

示例 1:

输入: 1
输出: [7]

示例 2:

输入: 2
输出: [8,4]

示例 3:

输入: 3
输出: [8,1,10]

提示:

  1. rand7 已定义。
  2. 传入参数: n 表示 rand10 的调用次数。

进阶:

  1. rand7()调用次数的 期望值 是多少 ?
  2. 你能否尽量少调用 rand7() ?
 1 # The rand7() API is already defined for you.
 2 # def rand7():
 3 # @return a random integer in the range 1 to 7
 4 
 5 class Solution:
 6     def rand10(self):
 7         """
 8         :rtype: int
 9         """
10         res = 0
11         while True:
12             res = rand7() + (rand7()-1)*7
13             if res <= 40:
14                 break
15 
16         return (res-1)//4 + 1
View Code

478. 在圆内随机生成点

难度中等

给定圆的半径和圆心的 x、y 坐标,写一个在圆中产生均匀随机点的函数 randPoint 。

说明:

  1. 输入值和输出值都将是浮点数
  2. 圆的半径和圆心的 x、y 坐标将作为参数传递给类的构造函数。
  3. 圆周上的点也认为是在圆中。
  4. randPoint 返回一个包含随机点的x坐标和y坐标的大小为2的数组。

示例 1:

输入: 
["Solution","randPoint","randPoint","randPoint"]
[[1,0,0],[],[],[]]
输出: [null,[-0.72939,-0.65505],[-0.78502,-0.28626],[-0.83119,-0.19803]]

示例 2:

输入: 
["Solution","randPoint","randPoint","randPoint"]
[[10,5,-7.5],[],[],[]]
输出: [null,[11.52438,-8.33273],[2.46992,-16.21705],[11.13430,-12.42337]]

输入语法说明:

输入是两个列表:调用成员函数名和调用的参数。Solution 的构造函数有三个参数,圆的半径、圆心的 x 坐标、圆心的 y 坐标。randPoint 没有参数。输入参数是一个列表,即使参数为空,也会输入一个 [] 空列表。

 1 import random
 2 
 3 
 4 class Solution:
 5 
 6     def __init__(self, radius: float, x_center: float, y_center: float):
 7         self.radius = radius
 8         self.x_center = x_center
 9         self.y_center = y_center
10         
11 
12     def randPoint(self) -> List[float]:
13         while True:
14             delta_x = random.uniform(-1.0,1.0)*self.radius
15             delta_y = random.uniform(-1.0,1.0)*self.radius
16             if pow(delta_x,2)+pow(delta_y,2) <= pow(self.radius,2):
17                 return [self.x_center+delta_x, self.y_center+delta_y]
18 
19 
20 # Your Solution object will be instantiated and called as such:
21 # obj = Solution(radius, x_center, y_center)
22 # param_1 = obj.randPoint()
View Code

猜你喜欢

转载自www.cnblogs.com/dede-0119/p/12557282.html