477. leetcode題目講解(Python):在圓內隨機生成點(Generate Random Point in a Circle )

題目如下:


我們可以獲取的信息爲:圓心座標(x,y),半徑。 所以,我們可以取得隨機點的座標範圍:

x :  [x-r, x+r]
y :  [y-r, y+r]

從圖形上表示,我們可以獲取一個正方形的範圍,如下圖所示:


因此通過random.uniform我們可以生成正方形內(包括邊上)的隨機點。但題目要求的是生成圓內的隨機點, 於是生成隨機點後可以通過點到圓心的距離來判斷隨機點是否在圓內,如果不在圓內,就拋棄該結果,重新生成。

參考代碼如下:

import random


class Solution:

    def __init__(self, radius: 'float', x_center: 'float', y_center: 'float'):
        self.radius = radius
        self.x_center = x_center
        self.y_center = y_center
        self.x_max = x_center + radius
        self.y_max = y_center + radius
        self.x_min = x_center - radius
        self.y_min = y_center - radius

    def randPoint(self) -> 'List[float]':
        while True:
            res_x = random.uniform(self.x_min, self.x_max)
            res_y = random.uniform(self.y_min, self.y_max)
            dis = (res_x - self.x_center)**2 + (res_y - self.y_center)**2
            if dis <= self.radius**2:
                return [res_x, res_y]

源碼地址:
https://github.com/jediL/LeetCodeByPython

其它題目:[leetcode題目答案講解彙總(Python版 持續更新)]
(https://www.jianshu.com/p/60b5241ca28e)

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

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