python3 The operation of changing factorial into function form for calling

  • 2021-09-24 22:53:46
  • OfStack

Define a function and find the factorial of a number, for example, find 5!

# Method 1, recursion


def jc(num):
  if num==1:
    return 1
  else:
    return num*jc(num-1)
print(jc(5)) # Return 120

# Method 2, for traversal


def func(num):
  ' Seek 1 The factorial of a number, such as 5 ! '
  sum=1
  for i in range(1,num+1):
    sum=sum*i # Can be simplified sum*=i
  return sum
func(5)
print(func(5))# Return 120

# Method 3, lambda expression write

# lambda cannot call arrays, such as lists.

# Here need to use a function to do (this function calls lambda expression as a parameter, that is, need to use a higher-order function reduce # Use a higher-order function, need to call a module # Change factorial into a function form to call functools


from functools import reduce
print(reduce(lambda x,y:x*y,range(1,6)))

Add: Python has very little code to implement factorial functions


from functools import reduce
def my_factorial(x):
  if x < 0:
    raise ValueError(' Parameter cannot be negative ')
  return reduce(lambda x, y: x*y, range(1, x+1)) if x != 0 else 1

Run results:


>>> for i in range(10):
...   print(my_factorial(i), end=' ')
>>> 1 1 2 6 24 120 720 5040 40320 362880

Functions can be easily defined by using lambda, reduce, filter, map, etc.


Related articles: