函数fact(n):计算阶乘 fact(n) = n! = 1x2x3x ... x (n-1)x n = (n-1)! x n = fact(n-1) x n 故act(n)可以表示为n x fact(n-1),只有n=1时需要特殊处理。 所以可以在n=1时,返回1 于是代码: #! /usr/bin/python3
# -*- coding:UTF-8 -*-
def fact(n):
if n==1:
return 1
return n * fact(n - 1)
print(fact(5))
|
|