Write the docstring for the following recursive function:
def mystery(a_list):
if len(a_list) <= 1:
return True
else:
return (a_list[0] <= a_list[1]) and mystery(a_list[1:])
Try to describe the recursive relationship in a single sentence.
Write a recursive function named rec_min
that takes a non-empty list as a parameter and returns the minimum value in the list. You must implement this recursively (no loops!) and should not use the min
function.
Write a function named rec_in
that takes two parameters, a list and an item, and returns True if that item is in the list, and False otherwise. You must implement this recursively (no loops!) and should not use functions like index
, count
, or in
.
The Fibonacci numbers are the following:
1, 1, 2, 3, 5, 8, 13, 21, ...
The nth Fibonacci number is defined as the sum of the previous two Fibonacci numbers (and the first two numbers are both 1). So, the 3rd Fibonacci number is 2, the 4th Fibonacci number is 3, etc.
Write a function named fib
that takes a number n as a parameter and
returns the nth Fibonacci number. Your function must be a recursive
function.
Check out the solution for fib
. Assuming you invoked fib(4)
, what is the argument to fib
every time it is invoked, in the order in which the fib
function would be invoked. The first argument would be 4.
Your recursive fib
function calculates the correct answer, but isnâ€™t
efficient. Try calling your function to calculate the 100th Fibonacci
number. Why is your recursive implementation so slow?
To help answer this question count how many times fib
would be called when
you invoke fib(5)
.
What will the following code draw assuming that the turtle starts at the origin, (0, 0), and pointing to the right?
from turtle import *
def mystery(x):
if x < 10:
dot(x)
else:
forward(x/2)
backward(x)
forward(x/2)
left(45)
mystery(x/2)
mystery(40)
What does the following code print?
def print_tree_lengths(width, depth):
if width < 2:
return
print(" "*depth, width)
print_tree_lengths(width//2, depth + 1)
print_tree_lengths(width//2, depth + 1)
print_tree_lengths(8, 0)