A fractal is a never-ending pattern. Fractals are infinitely complex patterns that are self-similar across different scales. They are created by repeating a simple process over and over in an ongoing feedback loop. Driven by recursion, fractals are images of dynamic systems – the pictures of Chaos.
In this article, we will draw a colorful Y fractal tree using a recursive technique in Python.
Examples:Output for depth level: (a) 14 (b) 12
Modules required
turtle:turtle library enables users to draw picture or shapes using commands, providing them with a virtual canvas. turtle comes with Python's Standard Library. It needs a version of Python with Tk support, as it uses tkinter for the graphics.
Functions used:
fd(x) : draw the cursor forward by x pixels.
rt(x), lt(x) : rotates the facing direction of the cursor by x degrees to the right and left respectively.
colormode(): to change the colour mode to rgb.
pencolor(r, g, b): to set the colour of the turtle pen.
speed(): to set the speed of the turtle.
Approach :
We start by drawing a single 'Y' shape for the base(level 1) tree. Then both the branches of the 'Y' serve as the base of other two 'Y's(level 2).
This process is repeated recursively and size of the Y decreases as level increases.
Colouring of the tree is done level wise: darkest in the base level to lightest in the topmost.
In the implementation below, we will draw a tree of size 80 and level 7.
Python3 1==
fromturtleimport*speed('fastest')# turning the turtle to face upwardsrt(-90)# the acute angle between# the base and branch of the Yangle=30# function to plot a Ydefy(sz,level):iflevel>0:colormode(255)# splitting the rgb range for green# into equal intervals for each level# setting the colour according# to the current levelpencolor(0,255//level,0)# drawing the basefd(sz)rt(angle)# recursive call for# the right subtreey(0.8*sz,level-1)pencolor(0,255//level,0)lt(2*angle)# recursive call for# the left subtreey(0.8*sz,level-1)pencolor(0,255//level,0)rt(angle)fd(-sz)# tree of size 80 and level 7y(80,7)
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.