Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
| Download

📚 The CoCalc Library - books, templates and other resources

Views: 96165
License: OTHER
1
"""This module contains a code example related to
2
3
Think Python, 2nd Edition
4
by Allen Downey
5
http://thinkpython2.com
6
7
Copyright 2015 Allen Downey
8
9
License: http://creativecommons.org/licenses/by/4.0/
10
"""
11
12
from __future__ import print_function, division
13
14
import copy
15
16
from Point1 import Point, Rectangle, print_point
17
from Point1_soln import distance_between_points
18
19
20
class Circle:
21
"""Represents a circle.
22
23
Attributes: center, radius
24
"""
25
26
27
def point_in_circle(point, circle):
28
"""Checks whether a point lies inside a circle (or on the boundary).
29
30
point: Point object
31
circle: Circle object
32
"""
33
d = distance_between_points(point, circle.center)
34
print(d)
35
return d <= circle.radius
36
37
38
def rect_in_circle(rect, circle):
39
"""Checks whether the corners of a rect fall in/on a circle.
40
41
rect: Rectangle object
42
circle: Circle object
43
"""
44
p = copy.copy(rect.corner)
45
print_point(p)
46
if not point_in_circle(p, circle):
47
return False
48
49
p.x += rect.width
50
print_point(p)
51
if not point_in_circle(p, circle):
52
return False
53
54
p.y -= rect.height
55
print_point(p)
56
if not point_in_circle(p, circle):
57
return False
58
59
p.x -= rect.width
60
print_point(p)
61
if not point_in_circle(p, circle):
62
return False
63
64
return True
65
66
67
def rect_circle_overlap(rect, circle):
68
"""Checks whether any corners of a rect fall in/on a circle.
69
70
rect: Rectangle object
71
circle: Circle object
72
"""
73
p = copy.copy(rect.corner)
74
print_point(p)
75
if point_in_circle(p, circle):
76
return True
77
78
p.x += rect.width
79
print_point(p)
80
if point_in_circle(p, circle):
81
return True
82
83
p.y -= rect.height
84
print_point(p)
85
if point_in_circle(p, circle):
86
return True
87
88
p.x -= rect.width
89
print_point(p)
90
if point_in_circle(p, circle):
91
return True
92
93
return False
94
95
96
def main():
97
box = Rectangle()
98
box.width = 100.0
99
box.height = 200.0
100
box.corner = Point()
101
box.corner.x = 50.0
102
box.corner.y = 50.0
103
104
print(box.corner.x)
105
print(box.corner.y)
106
107
circle = Circle
108
circle.center = Point()
109
circle.center.x = 150.0
110
circle.center.y = 100.0
111
circle.radius = 75.0
112
113
print(circle.center.x)
114
print(circle.center.y)
115
print(circle.radius)
116
117
print(point_in_circle(box.corner, circle))
118
print(rect_in_circle(box, circle))
119
print(rect_circle_overlap(box, circle))
120
121
122
if __name__ == '__main__':
123
main()
124
125
126