Lab 12: Part 1: Non-fruitful Recursion
Create a new file called lab12.py
. All the functions you write today will be recursive, and in this section, non-fruitful. Your functions will print, but not return values. Later on today, you'll move on to fruitful recursive functions.
Task 0. divideBy3
Write a function called divideBy3
that will take a number and
divide the number by 3, printing the number unless it is less than or equal to 1.
This function must be recursive.
>>> divideBy3(3)
3
>>> divideBy3(1)
>>> divideBy3(0)
>>> divideBy3(-4)
>>> divideBy3(15)
15
5.0
1.6666666666666667
>>> divideBy3(100)
100
33.333333333333336
11.111111111111112
3.703703703703704
1.234567901234568
Task 1. Recursive triangles
In this task, you will create some recursive patterns using asterisks.
Write a Python function called asteriskTriangle
that will take a length
parameter and draw a triangle pattern composed of lines of asterisks that get successively smaller with each line.
This function must be recursive.
Example invocations of asteriskTriangle
:
>>> asteriskTriangle(1)
*
>>> asteriskTriangle(3)
***
**
*
>>> asteriskTriangle(5)
*****
****
***
**
*
>>> asteriskTriangle(15)
***************
**************
*************
************
***********
**********
*********
********
*******
******
*****
****
***
**
*
>>> asteriskTriangle(0)
>>>
Task 2. switch
Write a function called switch
that will take a length parameter and draw a pattern like the examples below. The examples below always use asterisks and dashes:*
and -
. You can change those if you like, or, even better, add parameters so the user can specify their own symbols. This function must be recursive.
>>> switch(0)
>>> switch(1)
>>> switch (2)
**
>>> switch(3)
***---
**
---***
>>> switch(6)
******------
*****-----
****----
***---
**
---***
----****
-----*****
------******
>>> switch(8)
********--------
*******-------
******------
*****-----
****----
***---
**
---***
----****
-----*****
------******
-------*******
--------********
Table of Contents
- Lab 12 Home
- Part 0: Non-fruitful recursion Warm up
- Part 1: Non-fruitful Recursive Characters
- Part 2: Fruitful Recursion I
- Part 3: Fruitful Recursion II
- Reference: Recursive Design Patterns
- Knowledge Check