Jun Yang
Jun Yang

Reputation: 1

Problems of defining a factorial function in python

I'm recently starting to learn coding in Python, this is the code that I tried to define a function that helps me to find the factorial of a number. Yet, this chunk of code always returns me the double of its factorial.

def factorial(x):
   empty = None
   try:
      adj_x = int(x)
   except:
      print("Invalid Input")
   if adj_x < 0:
      print("Invalid Input")
   elif adj_x == 0:
      print(0)
   else:
      l_adj_x = adj_x - 1 # if input == 4, this is 3
      r = range(1, l_adj_x) # 1, 2, 3
      for k in r:
         n = adj_x - k # 4-1 = 3, 4-2 = 2, 4-3 = 1
         if empty is None:
            empty = n
         else:
            empty = empty * n
         n_adj_x = adj_x * empty * n
      print(n_adj_x)

I realized that it is the problem of the n in this line:

n_adj_x = adj_x * empty * n

Based on my own understanding, the last n in the for-loop should be 1 (I took 4 as an example of my input and stated all the possible outcomes of the loop in the comments next to each line of code) , if so, why does it appear to be the double of the correct answer (when I include n in n_adj_x = adj_x * empty * n) since the n should equal to 1?

Upvotes: 0

Views: 68

Answers (1)

Alexander
Alexander

Reputation: 17291

If what you are trying to get is the factorial here are some examples:

Example 1

n = 10
factorial = 1
for i in range(1,n+1):
    factorial *= i
print(factorial)

Example 2 <-- worst option
Slowest option and requires the most additional memory.

def fact(x):
    if x <= 1:
        return 1
    return x * fact(x - 1)
print(fact(10))

Example 3 <-- Best option

import math
print(math.factorial(10))

This is the python libs built in function and probably performs better than my simple loop, however I have not tested it.

Upvotes: 1

Related Questions