In Python Define a recursive function accepts a number as a parameter and return
ID: 3935367 • Letter: I
Question
In Python
Define a recursive function accepts a number as a parameter and returns a dictionary. The dictionary should contain, as a key, every number from 1 to the given number. The corresponding value for each key should be the factorial of that number. You may not use any looping in your solution.
Parameter(s): 1. A single positive integer.
Return Value: A dictionary containing each integer and it’s corresponding factorial.
Example(s): >>> print(factorial_dictionary(1)) {1: 1}
>>> print(factorial_dictionary(5)) {1: 1, 2: 2, 3: 6, 4: 24, 5: 120}
Explanation / Answer
Following python code should do the job :
def factorial_dictionary( N ):
result = {};
if N == 0:
return result;
if N == 1:
result[1] = 1;
return result;
result = factorial_dictionary( N - 1 );
result[N] = result[N-1]*N;
return result;
print( factorial_dictionary(1) );
print( factorial_dictionary(5) );
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.