一个练习题

15-1

定义一个新的名为Circle的类表示圆形,它的属性有center和radius,其中center是一个Point对象,而radius是一个数。
实例化一个Circle对象来代表一个圆心在(150, 100)、半径为75的圆形。
编写一个函数point_in_circle,接收一个Circle对象和一个Point对象,并当Point处于Circle的边界或其内时返回True。
编写一个函数rect_in_circle,接收一个Circle对象和一个Rectangle对象,并在Rectangle的任何一个角落在Circle之内时返回True。另外,还有一个更难的版本,需要在Rectangle的任何部分都落在圆圈之内时返回True。

import math
import copy


class Point:
    """
    Represents a point in 2-D space.
    """


def distance_between_points(point1, point2):
    x = abs(point1.x - point2.x)
    y = abs(point1.y - point2.y)
    distance = math.sqrt(x ** 2 + y ** 2)
    return distance


class Circle:
    """
    Represents a circle.

    attributes: point, radius
    """


def point_in_circle(circle, point):
    distance = distance_between_points(circle.center, point)
    if distance <= circle.radius:
        return True
    else:
        return False


class Rectangle:
    """Represents a rectangle.

    attributes: width, height, corner.
    """


def find_center(rect):
    """Returns a Point at the center of a Rectangle.

    rect: Rectangle

    returns: new Point
    """
    p = Point()
    p.x = rect.corner.x + rect.width / 2.0
    p.y = rect.corner.y + rect.height / 2.0
    return p


def rect_in_circle(circle, rectangle):
    p1 = Point()
    p1.x = rectangle.corner.x + rectangle.width
    p1.y = rectangle.corner.y + rectangle.height

    p2 = copy.deepcopy(p1)
    p2.x = rectangle.corner.x

    p3 = copy.deepcopy(p1)
    p3.y = rectangle.corner.y
    if point_in_circle(circle, rectangle.corner) or point_in_circle(circle, p1) or point_in_circle(circle, p2) or point_in_circle(circle, p3):
        return True

    else:
        return False


def main():
    blank = Point()
    blank.x = 40
    blank.y = 30

    circle = Circle()
    circle.radius = 100
    circle.center = Point()
    circle.center.x = 150
    circle.center.y = 100

    print(point_in_circle(circle, blank))

    box = Rectangle()
    box.width = 100.0
    box.height = 100.0
    box.corner = Point()
    box.corner.x = 0.0
    box.corner.y = 0.0

    print(rect_in_circle(circle, box))


if __name__ == '__main__':
    main()

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容