# Recursion Lab Solutions # CS111 # recursiveCharacters.py # ------------------------------------ # Task 0 # ------------------------------------ def divideBy3(n): '''A non-fruitful recursive function that prints each successive number, starting with n, divided by 3, until a number is less than 1 or equal to 1. ''' if n > 1: # Implicit base case if n <= 1, nothing happens. print(n) # Recursive case divideBy3(n/3) # ------------------------------------ # Task 1 # ------------------------------------ def asteriskTriangle(length): ''' A non-fruitful recursive function that prints inverted triangles composed of successively shorter lines of * ''' if length > 0: # Implicit base case (if length <=0, nothing happens) print('*' * length) asteriskTriangle(length - 1) # recursive call # Tests: #asteriskTriangle(5) # ------------------------------------ # Task 2 # ------------------------------------ def bowtie(n): ''' A non-fruitful recursive function that prints a sideways bowtie pattern that looks like this: ***** **** *** ** * ** *** **** ***** Note: this function is similar to the BOTH function in the lab worksheet ''' if n<=1: # base case print('*') else: print('*'*n) bowtie(n-1) # recursive call print('*'*n) # ------------------------------------ # Task 3 # ------------------------------------ def switch(size1): ''' A non-fruitful recursive function that prints a pattern that switches between * and -. Below is an example of switch(4): ****---- ***--- ** ---*** ----**** ''' if size1<=2: # base case print('*'*size1) else: print('*'*size1 + '-'*size1) switch(size1-1) # recursive call, sandwiched between two print statements print('-'*size1 + '*'*size1)