Added Exercise 4
This commit is contained in:
parent
a3b6ecf098
commit
aa4c1e23a5
65
ex_01_04.py
Normal file
65
ex_01_04.py
Normal file
|
@ -0,0 +1,65 @@
|
||||||
|
#!/usr/bin/python3
|
||||||
|
|
||||||
|
from util.io import readvalue
|
||||||
|
|
||||||
|
def positive_float(v):
|
||||||
|
x = float(v)
|
||||||
|
if(x <= 0):
|
||||||
|
raise ValueError("{} is a non-positive float".format(v))
|
||||||
|
return x
|
||||||
|
|
||||||
|
|
||||||
|
class Circle(object):
|
||||||
|
__slots__ = ["x", "y", "radius"]
|
||||||
|
|
||||||
|
def __init__(self, x, y, radius):
|
||||||
|
self.x = x
|
||||||
|
self.y = y
|
||||||
|
self.radius = radius
|
||||||
|
|
||||||
|
def has_intersection(self, other):
|
||||||
|
if(not isinstance(other, Circle)):
|
||||||
|
raise TypeError("cannot calculate intersection of Circle and {}".format(type(other)))
|
||||||
|
|
||||||
|
distance = ((self.x - other.x)**2 + (self.y - other.y)**2)**0.5
|
||||||
|
if(distance < self.radius + other.radius):
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
def __contains__(self, other):
|
||||||
|
if(not isinstance(other, Circle)):
|
||||||
|
raise TypeError("cannot calculate wether {} is in Circle".format(type(other)))
|
||||||
|
|
||||||
|
distance = ((self.x - other.x)**2 + (self.y - other.y)**2)**0.5
|
||||||
|
|
||||||
|
if(other.radius + distance < self.radius):
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def read_Circle():
|
||||||
|
radius = readvalue("radius> ", positive_float)
|
||||||
|
x = readvalue("x> ", float)
|
||||||
|
y = readvalue("y> ", float)
|
||||||
|
|
||||||
|
return Circle(x, y, radius)
|
||||||
|
|
||||||
|
|
||||||
|
if( __name__ == "__main__"):
|
||||||
|
print("Create Circle 1:")
|
||||||
|
c1 = Circle.read_Circle()
|
||||||
|
print("Create Circle 2:")
|
||||||
|
c2 = Circle.read_Circle()
|
||||||
|
|
||||||
|
print("\n")
|
||||||
|
|
||||||
|
if(c1.has_intersection(c2)):
|
||||||
|
print("The two circles have an intersection.")
|
||||||
|
else:
|
||||||
|
print("The two circles have no intersection.")
|
||||||
|
|
||||||
|
if(c2 in c1):
|
||||||
|
print("Circle 1 contains Circle 2")
|
||||||
|
if(c1 in c2):
|
||||||
|
print("Circle 2 contains Circle 1")
|
||||||
|
|
Loading…
Reference in New Issue
Block a user