BC_10_19_15

advertisement
CS 111 SI w/ Brenna
10/19/15
Recursion and Dictionaries
1. A recursive function is a function that calls _________________
2. A recursive function has two cases: a ____________ case where the function does not
invoke itself, and a _____________ case where the function invokes itself.
3. What would the following code do if invoked?
def printS (s, n):
print s
return printS(s,n-1)
4. What would the following code do if invoked?
def printS (s, n):
if n>0:
print s
return printS(s,n-1)
5. In the above function, label the base case, the recursive case, the functionality (the
work being done), and the argument being altered in the recursive case.
6. Write a dictionary comprehension that returns a dictionary whose keys are numbers 1
through 10 (inclusive) and whose values are the keys’ squares.
1. The Fibonacci sequence is as follows: 1, 1, 2, 3, 5, 8, 13, 21… where the first two
numbers are 1 and the following numbers are a sum of the previous two numbers. Write a
function that is recursive and will return the Fibonacci number of the nth index. Example:
fibRecursive(6) will return 8.
2. Fill in the rest of the function to make a dictionary whose keys are numbers and whose
values are words with a length of that number. Assume a function has already been
defined to read in words from a file, getLinesFromFile(filename).
def lengthDictionary(filename):
words = getLinesFromFile(filename)
# your part here
3. Write a function that returns the number of ways you can climb a staircase consisting
of n steps if you can take either 1- or 2-step turns. For example, if the staircase has 4
steps, you can climb it in these ways: (1,1,1,1); (1,1,2); (1,2,1); (2,1,1); and (2,2) for a
total of 5 ways.
Download