递归和迭代
# !/usr/bin/python3# -*- coding: utf-8 -*-
# @Time : 2023/2/8 22:18
# @Author : xiongming
# @File : Digui.py
# @Desc : 递归-recursion
# 递归:调用函数自身的过程
# 迭代比递归效率快
def funC(i):
# 条件限制
if i > 0:
print("AWDBYL", end='、')
i -= 1
funC(i)
funC(5)
print()
# 求一个数的阶乘:3!= 1 * 2 * 3
# 迭代器
def factIter(n):
result = n
for i in range(1,n):
result *= i
return print("结果是:" + str(result))
factIter(5)
# 递归
def factRecur(n):
if n == 1:
return 1
else:
return n * factIter(n-1)
# print(factRecur(5))
# 斐波那契数列 1,1,2,3,5,8,13
def fibIter(n):
a,b,c = 1,1,1
while n > 2:
c = a + b
a = b
b = c
n -= 1
return c
print(fibIter(8))
def fibRecur(n):
if n == 1 or n == 2:
return 1
else:
return fibIter(n-1) + fibIter(n-2)
print(fibRecur(8))
页:
[1]