0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

~ 再帰 ~ チートシート

Last updated at Posted at 2021-08-15

#目次
再帰の例
注意点

#はじめに

チートシートの扱いついてはここを読んでください

#再帰の例

recursion.py
def sum(num):
  if num == 1:
    return 1
  else:
    return sum(num-1)+num
ans.py
print(sum(100))

>>> 5050

1からnumまでの整数の和を求める関数
関数の中でその関数自身を呼び出すことで、ループして計算することができる

#注意点

ans.py
print(sum(10000))

>>> Traceback (most recent call last):
>>>   File "./Main.py", line 6, in <module>
>>>     print(sum(10000))
>>>   File "./Main.py", line 5, in sum
>>>     return sum(num-1)+num
>>>   File "./Main.py", line 5, in sum
>>>     return sum(num-1)+num
>>>   File "./Main.py", line 5, in sum
>>>     return sum(num-1)+num
>>>   [Previous line repeated 1887 more times]
>>>   File "./Main.py", line 2, in sum
>>>     if num == 1:
>>> RecursionError: maximum recursion depth exceeded

再帰の上限回数が決まっており、それを超えるとエラーを吐く(デフォルトでは1000回まで)
上限回数以上の再帰を行いたい場合は、以下のおまじないが必要

recursion.py
import sys
sys.setrecursionlimit(max_num) # 設定する上限回数をmax_numに入れる

しかし再帰の回数が多くなると計算時間が劇的に大きくなるので、そもそも再帰を使わず普通にfor文とかで同じ計算をした方がよい

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?