
Objective: Practice writing recursive functions in python3
Make the five recursive functions described below in python3 by using the starter code recursive_functions.py. For each function, figure out how to solve it conceptually : write down the base case (when recursion stops) and how each recursive function-call moves towards the base case. The functions should not print anything (except you may add temporary print statements to help debug them).
You can test your program by using the provided program test_recursive_functions.py. Don't edit the test program. Put it into the same directory (folder) with your recursive_functions.py and run it. It will import your functions as a module, test your functions, and tell you when each function is returning correct results.
1. Factorial
In math, if you have a number n, the factorial function (written n!) computes
n x (n-1) x (n-2) x (n-3) x ... x 1. For example:
-
0! is defined to be 1
-
1! = 1
-
2! = 2 x 1=2
-
3! = 3 x 2 x 1=6
-
4! = 4 x 3 x 2 x 1 = 24
-
5! = 5 x 4 x 3 x 2 x 1 = 120
Add your code to the provided function signature so it computes the factorial of the integer it is given. You may not use math.factorial() in your function.
2. Recursively Sum
Make a recursive function that takes an integer argument n and returns the sum of the
integers from 1 to n. E.g., if n=10, the function should return 55 (1 + 2 + 3 + . . . 10).
3. Recursively Sum List
Make a recursive function sumlist_recursively(l) that accepts a list of numbers as an argument, and returns the sum of all the numbers in the list. E.g., if the function is passed the list [1, 4, 8, 3, 0, 16], it should return 32.
4. Recursively Multiply
Make a recursive function that multiplies its two integer arguments (x and y) recursively. The function should return the value of x times y. Hint: multiplication can be performed as repeated addition, for example.:
7 x 4 = 4 + 4 + 4 + 4 + 4 + 4 + 4 = 28
5. Recursively Reverse a List
Mke a recursive function that reverses a list. For example, given [1, 2, 3, 4], the function
would return this list [4, 3, 2, 1]. It does not print anything.
starter code recursive_function.py:
def factorial(n):
pass # replace this line with your lines of recursive code
def sum_recursively(n):
pass # replace this line with your lines of recursive code
def sumlist_recursively(l):
pass # replace this line with your lines of recursive code
def multiply_recursively(n, m):
pass # replace this line with your lines of recursive code
def reverse_recursively(l):
pass # replace this line with your lines of recursive code
test_recursive_functions.py:
import recursive_functions
import math
def main():
# Test factorial
print('Testing factorial.')
assert recursive_functions.factorial(0) == 1
assert recursive_functions.factorial(1) == math.factorial(1) == 1
assert recursive_functions.factorial(2) == math.factorial(2) == 2
assert recursive_functions.factorial(5) == math.factorial(5) == 120
assert recursive_functions.factorial(7) == math.factorial(7) == 5040
print('All tests pass for `factorial` (✿◠‿◠)\n')
# Test sum_recursively
print('Testing sum_recursively.')
assert recursive_functions.sum_recursively(0) == 0
assert recursive_functions.sum_recursively(1) == sum(range(1+1)) == 1
assert recursive_functions.sum_recursively(2) == sum(range(2+1)) == 3
assert recursive_functions.sum_recursively(10) == sum(range(10+1)) == 55
print('All tests pass for `sum_recursively` (✿◠‿◠) ')
# Test sumlist_recursively(l)
print('Testing sumlist_recursively.')
assert recursive_functions.sumlist_recursively([1,2,3]) == sum([1,2,3])
assert recursive_functions.sumlist_recursively([42,16,99,102,1]) == sum([42,16,99,102,1])
assert recursive_functions.sumlist_recursively([17,13,9,5,1]) == sum([17,13,9,5,1])
print('All tests pass for r_sumlist (✿◠‿◠)\n')
# Test multiply_recursively
print('Testing multiply_recursively.')
assert recursive_functions.multiply_recursively(5, 1) == 5*1 == 5
assert recursive_functions.multiply_recursively(7, 4) == 7*4 == 28
print('All tests pass for `multiply_recursively` (✿◠‿◠)\n')
# Test reverse_recursively
print('Testing reverse_recursively.')
assert recursive_functions.reverse_recursively([1, 2, 3, 4]) == [4, 3, 2, 1]
life = ['born', 'grow up', 'grow old']
assert recursive_functions.reverse_recursively(life) == ['grow old', 'grow up', 'born']
print('All tests pass for `reverse_recursively` (✿◠‿◠)\n')
main()

Trending nowThis is a popular solution!
Step by stepSolved in 3 steps with 1 images

- Could you comment on the significance of the act of programming functions?arrow_forwardAssignment -> Operator Precedence: Write a program to show the difference in the precedence of prefix and postfix increment operators. The difference must be clear from the output of your program.arrow_forwardC++ Programmingarrow_forward
- def optimize_tail_calls(original_scheme_eval): """Return a properly tail recursive version of an eval function.""" def optimized_eval(expr, env, tail=False): """Evaluate Scheme expression EXPR in Frame ENV. If TAIL, return an Unevaluated containing an expression for further evaluation. """ if tail and not scheme_symbolp(expr) and not self_evaluating(expr): return Unevaluated(expr, env) result = Unevaluated(expr, env) # fill in code code here while isinstance(result, Unevaluated): #code here return optimized_eval scheme_eval = optimize_tail_calls(scheme_eval)arrow_forwardWrite a function named contains-double in Scheme that takes a list as input and returns true if an item every appears twice in a row. You may assume the list is flat (i.e., no nested lists).arrow_forwardWhy are functions even necessary in the first place in the world of programming?arrow_forward
- Assignment 16: Iteration Control Structure - Hands on practice Hint: Consider numbers 1 to 10, for each number find the odd multiples. Example, for 1, it should be 1, 3, 5, 7, 9 Objective: Given a real world problem, implement the logic and solve the problem using appropriate constructs (sequen- tial, selection, iteration) using an object oriented program- ming language (Java) for 2, it should be 2, 6, 10, 14, 18 Estimated time: 50 minutes Summary of this assignment: In this assignment, you have learnt the implementation of iteration control structures. Problem Description: Write simple java programs to implement the following prob- lems. 1.Find the sum of first 5 numbers (1 to 5) using for loop End of document statement 2.Find the product of first 5 numbers (1 to 5) using while loop statement 3. Generate the multiplication table of 10 upto multiple value 500 4.Calculate the square of first 5 numbers (1 to 5) using do..while statement 5.Find the odd multiples among the first 10…arrow_forwardCould you comment on the significance of the act of programming functions?arrow_forwardIs it possible to explain the importance of function creation in programming?arrow_forward
- Computer Networking: A Top-Down Approach (7th Edi...Computer EngineeringISBN:9780133594140Author:James Kurose, Keith RossPublisher:PEARSONComputer Organization and Design MIPS Edition, Fi...Computer EngineeringISBN:9780124077263Author:David A. Patterson, John L. HennessyPublisher:Elsevier ScienceNetwork+ Guide to Networks (MindTap Course List)Computer EngineeringISBN:9781337569330Author:Jill West, Tamara Dean, Jean AndrewsPublisher:Cengage Learning
- Concepts of Database ManagementComputer EngineeringISBN:9781337093422Author:Joy L. Starks, Philip J. Pratt, Mary Z. LastPublisher:Cengage LearningPrelude to ProgrammingComputer EngineeringISBN:9780133750423Author:VENIT, StewartPublisher:Pearson EducationSc Business Data Communications and Networking, T...Computer EngineeringISBN:9781119368830Author:FITZGERALDPublisher:WILEY





