A memo of writing a basic function in Python using recursion

I had a hard time understanding recursion, so I thought I'd put it together for myself. We may add more in the future. The language is Python3.

What is a recursive function?

--A recursive function is a function that calls itself within a function. --Must be implemented so that it always ends somewhere --The method used in the ** Divide and Conquer Act ** to divide a large problem into smaller problems and solve them.

Recursive function to find the sum from 1 to n

sum.py


def sum(n):
    if n <= 1:
        return n
    return n + sum(n-1)
    
print(sum(100))    # 5050

sum.py


def sum(n):
    res = 0
    if n >= 1:
        res = n + sum(n-1)
    return res

print(sum(100))    # 5050

Recursive function to find the factorial of n

factorical.py


def fractorial(n):
    if n <= 1:
        return n
    return n * fractorial(n-1)
    
print(fractorial(5))    # 120

factorical.py


def factorial(n):
    res = 1
    if n >= 1:
        res = n * factorial(n-1)
    return res
   
print(factorial(5))    # 120

A recursive function that finds a list that doubles each element of the list

def double_list(lst):
    if lst == []:
        return []
    
    first = lst[0]
    rest = lst[1:]
    
    return [first*2] + double_list(rest)
    
print(double_list([1,2,3]))    # [2, 4, 6]

An easy-to-understand explanation is here

Euclidean algorithm

euclidean.py


def gcd(m, n):
    r = m % n
    if r == 0:
        return n
    return gcd(n, r)

print(gcd(1071, 1029))   # 21

reference

The simplest example for understanding recursive functions [Recursive functions understood in Python] (https://qiita.com/dhirabayashi/items/2f079e62fa2e286f1766) [Understanding recursive functions in Python] (https://note.com/shimakaze_soft/n/nf17633fe257c) The idea of making a loop a recursive function

Impressions

It's hard to imagine recurrence and I'm still struggling ... The code looks simple, but it takes time to figure out how it works. That point for statement is easy to understand, isn't it?

Recommended Posts

A memo of writing a basic function in Python using recursion
Draw a graph of a quadratic function in Python
Get the caller of a function in Python
A memo about writing merge sort in Python
Create a function in Python
Ssh connection memo using ProxyCommand of ssh_config in Python
A memo when creating a directed graph using Graphviz in Python
How to develop in a virtual environment of Python [Memo]
To return char * in a callback function using ctypes in Python
Try running a function written in Python using Fn Project
When writing a program in Python
[Python] A memo of frequently used phrases (by myself) in Python scripts
A function that measures the processing time of a method in python
(Bad) practice of using this in Python
Precautions when pickling a function in python
Display a list of alphabets in Python 3
Scraping a website using JavaScript in Python
Draw a tree in Python 3 using graphviz
Meaning of using DI framework in Python
Basic Python writing
Effective Python Memo Item 4 Write a helper function instead of a complicated expression
[Python] [Word] [python-docx] Try to create a template of a word sentence in Python using python-docx
A memo of a tutorial on running python on heroku
Create a GIF file using Pillow in Python
A memo that I wrote a quicksort in Python
To execute a Python enumerate function in JavaScript
Make a copy of the list in Python
View drug reviews using a list in Python
Make a joyplot-like plot of R in python
Output in the form of a python array
Get a glimpse of machine learning in Python
Create a MIDI file in Python using pretty_midi
A well-prepared record of data analysis in Python
Basic story of inheritance in Python (for beginners)
Summary of Excel operations using OpenPyXL in Python
[Circuit x Python] How to find the transfer function of a circuit using Lcapy
Perform "diagonalization of symmetric matrix A using orthogonal matrix U" in Python (eigenvalue decomposition)
Basic data frame operations written by beginners in a week of learning Python
Extract elements (using a list of indexes) in a NumPy style from a Python list / tuple
Basic sorting in Python
Python basic memo --Part 2
Basic Python command memo
Basic knowledge of Python
Python basic grammar memo
Python basic memo --Part 1
[Python] Implementation of clustering using a mixed Gaussian model
Create a data collection bot in Python using Selenium
A memo connected to HiveServer2 of EMR with python
Basics of I / O screen using tkinter in python3
Cut a part of the string using a Python slice
A collection of code often used in personal Python
A memorandum when writing experimental code ~ Logging in python
The pain of gRPC using Python. November 2019. (Personal memo)
Group by consecutive elements of a list in Python
Solve the one-stroke writing (backtrack without recursion in Python)
Display a histogram of image brightness values in python
A collection of Excel operations often used in Python
A python regular expression, or a memo of a match object
How to execute a command using subprocess in Python
A reminder about the implementation of recommendations in Python
I tried using Python (3) instead of a scientific calculator