W The Procedure Mondrian A couple of features to make the design more

# W the procedure mondrian a couple of features to make

This preview shows page 34 - 48 out of 60 pages.

W The Procedure Mondrian A couple of features to make the design more interesting: (1) The dart throw that determines the subdivision can’t land too near the edge. No super skinny tiles! (2) Randomly decide whether or not to subdivide. This creates a nice diversity in size. Next Up A Non-Graphics Example of Recursion: The Factorial Function Recursive Evaluation of Factorial Recall the factorial function: def F(n): x = 1 for k in range(1,n+1): x = x*k return x 5! = 1x2x3x4x5 Recursive Evaluation of Factorial Q. How would you compute 6! given that you have computed 5! = 120 ? 5! = 1x2x3x4x5 A. 6! = 120 x 6 Recursive Evaluation of Factorial How does this work? def F(n): if n<=1: return 1 else: a = F(n-1) return n*a Executing F(3) m = 3 x = F(m) print x We are in the calling script m -> x --> 3 Executing F(3) m = 3 x = F(m) print def F(n): if n<=1: return 1 else: a = F(n-1) return n*a The function F is called with argument 3. We open up a call frame. m -> x --> 3 n -> a --> return 3 Executing F(3) m = 3 x = F(m) print x def F(n): if n<=1: return 1 else: a = F(n-1) return n*a We encounter a function call. F is called with argument equal to 2. m -> x --> 3 n -> a --> return 3 Executing F(3) m = 3 x = F(m) print x def F(n): if n<=1: return 1 else: a = F(n-1) return n*a We open up a call frame. def F(n): if n<=1: return 1 else: a = F(n-1) return n*a m -> x --> 3 n -> a --> return 2 n -> a --> return 3 Executing F(3) m = 3 x = F(m) print x def F(n): if n<=1: return 1 else: a = F(n-1) return n*a We encounter a function call. F is called with argument 1 def F(n): if n<=1: return 1 else: a = F(n-1) return n*a m -> x --> 3 n -> a --> return 2 n -> a --> return 3 Executing F(3) m = 3 x = F(m) print x def F(n): if n<=1: return 1 else: a = F(n-1) return n*a We open up a call frame. def F(n): if n<=1: return 1 else: a = F(n-1) return n*a m -> x --> 3 n -> a --> return 2 n -> a --> return 3 def F(n): if n<=1: return 1 else: a = F(n-1) return n*a n -> a --> return 1 Executing F(3) m = 3 x = F(m) print x def F(n): if n<=1: return 1 else: a = F(n-1) return n*a The value of 1 is “assigned” to return def F(n): if n<=1: return 1 else: a = F(n-1) return n*a m -> x --> 3 n -> a --> return 2 n -> a --> return 3 def F(n): if n<=1: return 1 else: a = F(n-1) return n*a n -> a --> return 1 1 Executing F(3) m = 3 x = F(m) print x def F(n): if n<=1: return 1 else: a = F(n-1) return n*a The value is sent back to the caller.  #### You've reached the end of your free preview.

Want to read all 60 pages?

• • • 