# define Triangle class
class Triangle:
def __init__(self, height, width):
self.height = height
self.width = width
@property
def area(self):
return 0.5 * self.height * self.width
# initialise instances
tri1 = Triangle(5, 5)
tri2 = Triangle(5, 8)
# compare areas
tri1.area < tri2.area
True
from random import random
# initialise list of random triangles
triangles = [Triangle(10*random(), 10*random()) for i in range(10)]
# sorting inplace
triangles.sort(key = lambda x: x.area)
# print the sorted triangles and corresponding areas
for tri in triangles:
print( tri.area )
0.02262031409510108 1.9613063809417997 3.5747228774418245 5.328844861280842 5.535032025900612 6.543706546566132 10.914336423463437 11.597341952659397 12.142288392240784 18.616891800445224
# define Counter class
class Counter:
def __init__(self, start=0):
self.__value = start
def count_up(self):
self.__value += 1
def count_down(self):
self.__value -= 1
def get_value(self):
return self.__value
# initialise counter instance and take it for a spin
counter = Counter()
counter.count_up()
counter.count_up()
counter.count_up()
counter.count_down()
counter.get_value()
2
# define Counter class
class Counter:
def __init__(self, start=0):
self.__value = start
def count_up(self):
self.__value += 1
def count_down(self):
self.__value -= 1
def get_value(self):
return self.__value
def count_up_by(self, step):
self.__value += step
# initialise counter instance and take it for a spin
counter = Counter()
counter.count_up()
counter.count_up_by(5)
counter.count_down()
counter.get_value()
5
The cell below is for setting the style of this document. It's not part of the exercises.
# Apply css theme to notebook
from IPython.display import HTML
HTML('<style>{}</style>'.format(open('../css/cowi.css').read()))