Assignment 11-03
Assignment
1.Write the definition of a Point class. Objects from this class should have a
· a method show to display the coordinates of the point
· a method move to change these coordinates.
Solution :
'''the following code p class takes 2 arguments
the SHOW function returns the co-ordinates or point suppose (x,y)
the MOVE function takes 2 arguments (x1,y1) and moves the (x,y) point by (x1,y1)
the SHOW function displays the new co-ordinates
'''
class p(object):
def __init__(self, x, y):
self.x = x
self.y = y
def show(self):
return self.x, self.y
def move(self, x, y):
self.x += x
self.y += y
p1 = p(1,4)
p2 = p(2,5)
print(p1.show())
print(p2.show())
p1.move(5,6)
p2.move(7,8)
print(p1.show())
print(p2.show())
2.Write a Python class to implement pow(x, n)
Solution :
class p:
def pow(self, x, n):
if x == 0 or x == 1 or n == 1:
return x
if x == -1:
if n % 2 == 0:
return 1
else:
return -1
if n == 0:
return 1
if n < 0:
return 1/self.pow(x, -n)
val = self.pow(x, n//2)
#print(val)
if n % 2 == 0:
return val*val
return val*val*x
print(p().pow(2, 9))
print(p().pow(3, -3))
print(p().pow(-5,4 ))
3.Write a Python class named Circle constructed by a radius and two methods which will compute the area and the perimeter of a circle.
Solution :
class circle():
def __init__(self,r):
self.rad=r
def area(self):
return self.rad**2*3.14
def peri(self):
return self.rad*2*3.14
circle2 = circle(4)
print(circle2.area())
print(circle2.peri())
Comments
Post a Comment