LoginSignup
0
1

More than 1 year has passed since last update.

【Python】for文でもwhile文でもない、再帰関数を使ったループ処理

Last updated at Posted at 2021-06-04

概要

コードを書くときに度々登場するfor文やwhile文ですが、
実は再帰関数を使ってもループ処理ができるのです。

目次

  1. 再帰関数によるループ処理
  2. 処理速度の比較

1. 再帰関数によるループ処理

再帰関数によるループ処理
def loop(i):
    i -= 1 
    print('hello world')
    if i:
        return loop(i)
    return True

loop(3)
# 出力結果
# hello world
# hello world
# hello world

コードの説明

loop(3)を実行すると、loop(2),loop(1)と自身の関数を返し続ける。
loop(0)でif文を満たさないので、Trueを返す。

2. 処理速度の比較

それぞれ1万回2の1000乗を繰り返し計算して、処理速度を比較する。

処理速度の比較
import time
import sys
sys.setrecursionlimit(100000)

# 処理回数
n = 10000


def loop(i):
    i -= 1
    hoge = 2 ** 1000
    if i:
        return loop(i)
    return True


# loop(再帰関数)
start_loop = time.time()
loop(n)
print('loop:{:.5f} sec'.format(time.time() - start_loop))

# forループ
start_for = time.time()
for _ in range(n):
    hoge = 2 ** 1000
print('for:{:.5f} sec'.format(time.time() - start_for))

# whileループ
start_while = time.time()
while n > 0:
    n -= 1
    hoge = 2 ** 1000
print('while:{:.5f} sec'.format(time.time() - start_while))

# 出力結果
# loop:0.02358 sec
# for:0.01002 sec
# while:0.00886 sec

結果

ループ名 処理時間(sec)
再帰関数 0.02358
for文 0.01002
while文 0.00886

再起関数はfor文、while文に比べて2、3倍程度処理速度が遅い結果となった。実際に関数のループ処理を使う場面は少ないだろう。

補足

コード3行目の「sys.setrecursionlimit」は、関数の呼び出し回数の制限に関するもので、詳しくはPythonの再帰回数の上限を確認・変更を参照されたい。

参考記事

Pythonで理解する再帰関数

0
1
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
1