计算阶层
普通方法:
-使用循环
#!/usr/bin/python
def factorial(n):
sum = 1
for i in range(1,n+1):
sum *= i
return sum
print factorial(5)
计算阶层
python 7.py
120
#!/usr/bin/python
def factorial(n):
sum = 0
for i in range(1,n+1):
sum += i
return sum
print factorial(100)
100 求和
python 7.py
5050
递归的注意事项
必须有最后的默认结果
if n == 0
递归参数必须向默认结果收敛的:
factorial(n-1)
#!/usr/bin/python
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
print factorial(5)
递归方式计算阶层
#!/usr/bin/python
def factorial(n):
if n == 0:
return 0
else:
return n + factorial(n-1)
print factorial(100)
递归方式相加