类型:几何
方法:拒绝采样
力扣链接请移步 本题传送门
更多力扣中等题的解决方案请移步 力扣中等题目录
给定圆的半径和圆心的 x、y 坐标,写一个在圆中产生均匀随机点的函数 randPoint 。
说明:
输入值和输出值都将是浮点数。
圆的半径和圆心的 x、y 坐标将作为参数传递给类的构造函数。
圆周上的点也认为是在圆中。
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 没有参数。输入参数是一个列表,即使参数为空,也会输入一个 [] 空列表。
我们在以圆心为中心,以二倍半径为边长的正方形内部进行随机选点,当点落在圆内或者圆上时,满足条件,返回该点。
我们可以把上面的直角坐标变换为极坐标,随机的选取角度和半径,生成的点一定在圆上或者圆内。这里需要注意,由于在平面维度是均匀采样的,生成随机半径时需要对结果开方。
如有疑问或建议,欢迎评论区留言~
有关更多力扣中等题的python解决方案,请移步 力扣中等题解析
import randomimport numpy as np
List = np.array([(0,0),(1,1),(1.6,1.8),(3,3)])
d = 0.5
def get_random(low,high):
return((high-low)*random.random()+low)
n = 0
while n<100000:
x = get_random(0,3)
y = get_random(0,3)
rand_tuple = np.array([x,y])
tmp_dist = np.sqrt(np.sum(np.square(List-rand_tuple),axis = 1))
tmp_dist_bool = tmp_dist >= d
if np.sum(tmp_dist_bool) == len(List):
print(x,y)
break
n += 1
if n==100000:
print("After",n,"tries,can't get a random point!Check whether the problem has a solution!")
思路:1、定义一个字典,把名字和数字对应起来;2、引用随机模块;3、输入要点名的个数,通过循环输出名字。
具体代码如下:
# -*- coding:utf-8 -*-from random import randint
DictName = {1: 'Aaron',
2: 'Abel',
3: 'Abraham',
4: 'Adam',
5: 'Adrian',
6: 'Alva',
7: 'Alex',
8: 'Alexander',
9: 'Alan',
10: 'Albert',
11: 'Alfred',
12: 'Andrew',
13: 'Andy',
14: 'Angus',
15: 'Anthony',
16: 'Arthur',
17: 'Austin',
18: 'Ben',
19: 'Benson',
20: 'Bill',
21: 'Bob',
22: 'Brandon',
23: 'Brant',
24: 'Brent',
25: 'Brian',
26: 'Bruce',
27: 'Carl',
28: 'Cary',
29: 'Caspar',
30: 'Charles',
31: 'Cheney',
32: 'Chris',
33: 'Christian',
34: 'Christopher',
35: 'Colin',
36: 'Cosmo',
37: 'Daniel',
38: 'Dennis',
39: 'Derek',
40: 'Donald',
41: 'Douglas',
42: 'David',
43: 'Denny',
44: 'Edgar',
45: 'Edward',
46: 'Edwin',
47: 'Elliott',
48: 'Elvis',
49: 'Eric',
50: 'Evan',
51: 'Francis',
52: 'Frank',
53: 'Franklin',
54: 'Fred',
55: 'Gabriel',
56: 'Gaby',
57: 'Garfield',
58: 'Gary'}
Num = raw_input('请输入需要点名个数:')
flag = True
while flag:
if Num.isdigit():
Ind = int(Num)
flag = False
else:
print '输入错误,请确认'
else:
for i in range(Ind):
print DictName[randint(1,58)]
运行结果:
请输入需要点名个数:4
Brant
Cheney
David
Alan