 # Recursion - Factorial Functions Python Problem

## Question

Recursion - Factorial Functions

Objectives: practice with recursive and non-recursive iteration.

Instructions: In math, if you have a number n, the factorial function computes n * (n-1) * (n-2) * (n-3) * … * 1. An exclamation point (‘!’) is used to indicate taking the factorial of a number, e.g., n!.

For example: 0! is defined to be 1

1! = 1

2! = 2 * 1 = 2

3! = 3 * 2 * 1 = 6

4! = 4 * 3 * 2 * 1 = 24

5! = 5 * 4 * 3 * 2 * 1 = 120

Python’s math module provides a factorial function.

Programs that import math can then call math.factorial(n) to compute the factorial of any integer.

For this exercise, write three different versions of your own factorial function.

Put all three functions in one file: factorial.py:

factorial_while(n): using a while loop

factorial_for(n): using a for loop

factorial_recurse(n): using recursion

Do not use the math.factorial() function in your own factorial functions.

Your factorial functions should return their computed value; they should not print their value. Include a main() function that calls your factorial functions with test-numbers.

Your main() function should test the values returned by your factorial functions.

You may use math.factorial(n) to compare your functions, to make sure they return the same result.

Extra Credit:

Write a Python program multiply.py with a recursive function multiply(x,y) that accepts two arguments x and y.

The function should recursively return the value of x times y.

Hint: multiplication can be performed as repeated addition, such as: 7 x 4 = 4 + 4 + 4 + 4 + 4 + 4 + 4

So think about how many times you would be summing.

Extra Credit 2

Write a Python program reverse_list.py with a recursive function that reverses a list.

For example, given [1, 2, 3, 4], the function would return [4, 3, 2, 1].

Hint: you will need to concatenate two lists on every recursive call. Remember, this is just like the stack - First-In, Last-Out.

Hint 2: you will want to think about how to slice lists and how to access the last element in a list.

Hint 3: think about what the base case would be for a list.

## Solution Preview

This material may consist of step-by-step explanations on how to solve a problem or examples of proper writing, including the use of citations, references, bibliographies, and formatting. This material is made available for the sole purpose of studying and learning - misuse is strictly forbidden.

'''
factorial.py
'''

# factorial implemented with while loop
def factorial_while(n):
result = 1
while n > 1:
result *= n
n -= 1
return result

# factorial implemented with for loop
d...
\$45.00 for this solution

PayPal, G Pay, ApplePay, Amazon Pay, and all major credit cards accepted.

### Find A Tutor

View available Python Programming Tutors

Get College Homework Help.

Are you sure you don't want to upload any files?

Fast tutor response requires as much info as possible.