Python の学習 - 中級コース: 3 日目、Python での再帰


今日は、Python で再帰を学び、再帰関数を作成して、フィボナッチ数、階乗、コラッツ予想などの問題を解決します。




前の 2 つの部分では、ユーザー定義関数を作成し、値を返すようにする方法を学びました.見逃した方もぜひチェックしてみてくださいね!

再帰とは



Recursion is a way of approaching problems which breaks apart complex concepts into smaller and smaller solvable steps.



再帰は非常に貴重なプログラミング ツールです.再帰は、プログラミング原則の Divide and Rule の一例です.これは、元の問題を、元の問題に似ているがサイズが小さい 2 つ以上のサブ問題に分割して、問題を解決する方法です.副問題はさらに分割されます.次に、サブ問題の答えを組み合わせて、元の問題の答えを取得します.

再帰により、プログラマーはアルゴリズムの重要なステップに集中することができ、最初はそのステップを他のすべてのステップと結合することを心配する必要がありません.

再帰は、複雑な問題を解決するための最も柔軟で強力なツールの 1 つです.適切に実装すると、再帰はメモリ効率と時間効率が向上します. return ステートメントを忘れるなどのエラーは回避する必要があります.そうしないと、プログラムがブームに陥ります!

再帰の概念に慣れていない人のために、ここにいくつかのクイック リファレンスを示します.
  • Recursion is not hard: a step-by-step walkthrough of this useful programming technique
  • A quick guide to Recursion by example.
  • Recursion for Coding Interviews: The Ultimate Guide

  • 質問例 1- コラッツ予想の再帰バージョンを書いてください-




    def collatz(a):
        count=a[len(a)-1]
        if(count==1):
            return a
        if(count%2==0):
            a.append(count/2)
        else:
            a.append(count*3+1)
        return collatz(a)
    
    
    print(collatz([7]))
    



    [7, 22, 11.0, 34.0, 17.0, 52.0, 26.0, 13.0, 40.0, 20.0, 10.0, 5.0, 16.0, 8.0, 4.0, 2.0, 1.0]
    


    A common computer programming tactic is to divide a problem into sub-problems of the same type as the original, solve those sub-problems, and combine the results. This is often referred to as the divide-and-conquer method; when combined with a lookup table that stores the results of previously solved sub-problems (to avoid solving them repeatedly and incurring extra computation time), it can be referred to as dynamic programming or memoization. - Wikipedia




    n 番目のフィボナッチ数を再帰的に求めるプログラムを作成します。




    def fibo(n):
        if(n==1 or n==2):
            return 1 
        return fibo(n-1)+fibo(n-2)
    
    print(fibo(6))
    print(fibo(10))
    



    8
    55
    


    演習


  • 1) 階乗の再帰関数を書きなさい.
  • 2) for ループを使用せずに次の出力を与えるプログラムを作成します.

  • ******
    *****
    ****
    ***
    **
    *
    



    それが今日のすべてです.明日は、再帰関数をいくつか調べて、再帰のガイドラインを学びます.
    ✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨

    演習への回答は、私のプロフィールに固定されている Learning Python Repository で利用できます😃
    😎 あなたの提案は私をやる気にさせるので、この部分かどうかをコメント欄で教えてください. 🧐 投稿に「いいね!」を忘れずに. 😍