Lab 12, Fruitful recursion warm-up
Part 0
def sumUpTo(num):
if num > 0:
return num + sumUpTo(num-1)
What does sumUpTo(3)
return?
Part 1
In []: grabFirst([ ])
Out[]: [ ]
In []: grabFirst(['jen','rachel','faith'])
Out[]: ['j','r','f']
In []: grabFirst(['emma','sarah','abigail','bianca']
Out[]: ['e','s','a','b']
Write a function called grabFirst
that takes a list of strings and returns a list with
the first letter of each word from the original list. This function must be recursive and fruitful.
Hint: you can use list concatenation (+) to smush two lists together into one, like this:
['a', 'b'] + ['c'] will result in
['a', 'b', 'c']
Part 2 countDivides
Write a function called countDivides
that takes a number as parameter and returns the number of times
that the number can be halved until it is less than or equal to 1. This function must be fruitful and recursive.
Note that in the examples below, countDivides
prints the original number, followed by that number halved,
until the quotient is less than or equal to 1. The printing is just a side effect; the function returns the number of times that the original number can be halved until it is less than or equal to 1.
countDivides(100) returns 7
100
50.0
25.0
12.5
6.25
3.125
1.5625
0.78125
--
countDivides(17) returns 5
17
8.5
4.25
2.125
1.0625
0.53125
--
countDivides(8) returns 3
8
4.0
2.0
1.0
--
countDivides(2) returns 1
--
countDivides(1) returns 0
--
countDivides(0.5) returns 0
--
countDivides(0) returns 0
--
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