Pythonでの再帰関数
6241 ワード
さいきかんすう
再帰関数:自分で自分の関数を呼び出し、関数内で直接または間接的に自分で調整します.
【結果】
再帰は数学の「数学帰納法」に似ている.各再帰関数には、次の2つのセクションが含まれている必要があります.
1、終了条件
再帰関数がいつ終わるかを表し、一般的に値を返し、自分を呼び出さないようにします.
2、再帰手順
ステップnの値をステップn-1に関連付けます.
再帰関数は、大量の関数オブジェクトを作成するため、メモリと演算能力を消費します.
【結果】
行コードを追加
【結果】
階乗練習
【結果】
=1: return 1 else: return n*factorial(n-1)
result=factorial(5) print(result)
再帰関数:自分で自分の関数を呼び出し、関数内で直接または間接的に自分で調整します.
# 。
#test01 test02 , , 。
def test01():
print("test01")
test02()
def test02():
print("test02")
test01()
【結果】
test01
test02
再帰は数学の「数学帰納法」に似ている.各再帰関数には、次の2つのセクションが含まれている必要があります.
1、終了条件
再帰関数がいつ終わるかを表し、一般的に値を返し、自分を呼び出さないようにします.
2、再帰手順
ステップnの値をステップn-1に関連付けます.
再帰関数は、大量の関数オブジェクトを作成するため、メモリと演算能力を消費します.
#
def test01(n):
print("test01",n)
if n==0:
print("over")
else:
test01(n-1)
def test02():
print("test02")
test01(4)
【結果】
test01 4
test01 3
test01 2
test01 1
test01 0
over
行コードを追加
def test01(n):
print("test01",n)
if n==0:
print("over")
else:
test01(n-1)
print("test01***",n)
def test02():
print("test02")
test01(4)
【結果】
test01 4
test01 3
test01 2
test01 1
test01 0
over
test01*** 0
test01*** 1
test01*** 2
test01*** 3
test01*** 4
階乗練習
#
def factorial(n):
if n==1:
return 1
else:
return n*factorial(n-1)
result=factorial(5)
print(result)
【結果】
=1: return 1 else: return n*factorial(n-1)
result=factorial(5) print(result)
【 】
120