COMP 1800 Computing in Python SPRING 2021 DAVID















- Slides: 15

COMP 1800 Computing in Python SPRING, 2021 DAVID J. STUCKI

ALERTS Reading assignment: Chapter 9 (pp. 285 -305) Lab 9 due Tuesday, March 30 by 11: 59 p. m. Lab 10 (available this weekend) will be due 4/9. Questions?

Fractals § Geometrical objects that have the property of selfsimilarity § This means that parts of the whole are scaled copies of the whole § And parts of the parts are scaled copies of the whole § And so on. . .

Recursion § Fractals are defined (mathematically) in a recursive manner, and so are often drawn using recursive algorithms § A recursive method is one in which the body of the method contains a call to the method being defined § Some of you have done this accidentally. . . def hello(): print("Hello") hello() § A correct recursive algorithm will always have two parts: § Base case § Recursive case § These will generally be separated out by an if statement

© 2001– 2019 Python Software Foundation. All Rights Reserved. Visualizing Recursion: The Geometry of Nature

Recursion Example: Nested Squares § Base Case § Length of current square is less than 1: do nothing § Recursive Case § Draw a square of current length § Then call the function again with a smaller side length

Recursion def draw. Square(a. Turtle, side): for i in range(4): a. Turtle. forward(side) a. Turtle. right(90) def nest. Box(a. Turtle, side): if side >= 1: draw. Square(a. Turtle, side) nested. Box(a. Turtle, side - 5)

Recursion: List example § List algorithms are often implemented with recursion § Suppose that you want to count the number of elements def count(a. List): if a. List == []: return 0 else: return 1 + count(a. List[1: ]) § How does this work? § Base case? § Recursive case?

Recursion: Math example

Recursion: More Geometry § Fractal Trees: code. . . § Sierpinski Triangle § Code. . .

Recursion: More Geometry § Koch Snowflakes

L-Systems § Introduced and developed in 1968 by Aristid Lindenmayer , a Hungarian theoretical biologist and botanist at the University of Utrecht § A method of collapsing a recursive structure into a set of replacement rules that can be performed iteratively § Grammar § Axiom (starting symbol) § Rules (substitutions) § Example Axiom: A Rules: A → B B → AB

L-Systems Example Axiom: A Rules: A → B B → AB A B AB BAB Axiom Apply rule 1 to A Apply rule 2 to B Apply rule 1 to A, then rule 2 to B

L-Systems Example Axiom: A Rules: A → B B → AB A B AB BAB ABBAB BABABBAB Code. . . Axiom Apply rule 1 to A Apply rule 2 to B Apply rule 1 to A, then rule 2 to B Apply rule 2 to B, rule 1 to A, rule 2 to B Apply rules 1, 2, 2, 1, 2

Next time: No Lab Friday Monday: ◦ Chapter 10