## K-Means ClusteringÂ

```
importturtle
classTree:
def__init__(self, pen, n, width, length, width_ratio, length_ratio):
"""
Constructor which takes the following arguments
pen: The pen object from Turtle Graphics
n: How many sub-branches will be drawn
width: The width of the initial branch
length: The length of the initial branch
width_ratio: How much the width will be reduced for each sub-branch
length_ratio: How much the length will be reduced for each sub-branch
"""
self.pen= pen
self.n= n
self.width= width
self.length= length
self.width_ratio=width_ratio
self.length_ratio=length_ratio
self.colors= ['red', 'green', 'blue', 'yellow', 'orange', 'purple']
self.pen.speed('fastest') # Set turtle speed to fatest
self.pen.left(90) # Set initial direction to north
self.pen.width(self.width) # Set width
self.pen.forward(self.length) # draw line
self.pen.back(self.length) # return to initial pos
#self.pen.pendown()
self.pen.forward(self.length) # draw
self.draw_tree(self.length, self.n) # call draw function
defdraw_tree(self, branch_length, n):
width =self.pen.width() # current width
# Set pen color
self.pen.color(self.colors[n%len(self.colors)])
self.pen.width(width*(1-self.width_ratio)) # reduce width
branch_length=branch_length* (1-self.length_ratio) # reduce length
self.pen.left(30) # rotate to left
self.pen.forward(branch_length) # draw
# If n > 0 draw another branch
if n >0:
self.draw_tree(branch_length, n -1)
self.pen.back(branch_length)
self.pen.right(2*30)
self.pen.forward(branch_length)
# If n > 0 draw another branch
if n >0:
self.draw_tree(branch_length, n -1)
self.pen.back(branch_length)
self.pen.left(30)
self.pen.width(width) # restore old width
if __name__ =='__main__':
pen =turtle.Pen()
pen.goto(0, -100) # set initial position
n =8# number of branches/levels from initial branch
width =12# width of the initial branch
length =80# length of the initial branch
width_ratio=0.25# percent to reduce the width
length_ratio=0.25# percent to reduce the width
tree =Tree(pen, n, width, length, width_ratio, length_ratio)
turtle.done()
```