Home > Net >  Python Program to Find Factorial of Number Using Recursion
Python Program to Find Factorial of Number Using Recursion

Time:10-30

The factorial of a number is the product of all the integers from 1 to that number.

For example, the factorial of 6 is 12345*6 = 720. Factorial is not defined for negative numbers and the factorial of zero is one, 0! = 1.

def recur_factorial(n):
   if n == 1:
       return n
   else:
       return n*recur_factorial(n-1)

num = 7

# check if the number is negative
if num < 0:
   print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
   print("The factorial of 0 is 1")
else:
   print("The factorial of", num, "is", recur_factorial(num))

CodePudding user response:

I would like help just to know how to read the entries and call the functions

For that purpose you can add the following code below your functions:

# main program
method = {
    "IV": add_node,
    "IA": add_edge,
    "RV": delete_node,
    "RA": delete_edge
}
numinputlines = int(input())
for _ in range(numinputlines):
    instruction, *rest = input().split()
    if len(rest) == 3:  # There is a cost:
        rest[-1] = int(rest[-1])
    method[instruction](*rest)

The method dictionary helps to translate a 2-letter code to a method that needs to be called. As the arguments to those methods are all in the same order, you can just capture those in a list rest, and "unpack" that list when passing the arguments. There is just one special thing to take care of. Two methods get a cost argument, and it must be of number type. Since input is read as string, you need to convert that cost string to a number. The if statement takes care of this case.

This should answer your question, but it does not finish the exercise. You will still have to debug your code. For instance, currently your code will raise an exception on the example input you have given -- vertex "B" is referenced in IA B A 1 before it is added with IV B.

Also, you'll need to add the code to produce the output.

But since your question was about capturing the input and calling the functions, I have left the rest for you to tackle.

CodePudding user response:

How do I calculate a factorial of an integer in Python? Note that the factorial function is defined only for positive integers; therefore, you should also check that n >= 0 and that isinstance(n, int). Otherwise, raise a ValueError or a TypeError respectively.

def factorial(n): 
    if(not isinstance(n, int) or n < 0):
       raise ValueError("Invalid argument")

    if (n==1 or n==0):          
        return 1      
    else:          
        return (n * factorial(n - 1)) 
  
# Driver Code 
num = int(input("Please enter a number"))
print("Factorial : ",factorial(num))
  • Related