In Python Define a recursive function accepts a number as a

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}

Solution

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) );

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

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site