A note on handling variables in Python recursive functions

Python recursive function value

When I was building a recursive function, I verified it because I couldn't understand how the value outside the function was rewritten inside the function in python.

Prerequisite knowledge

Check how variables defined inside and outside the function are handled.

a=10
def replace1():
    a=15
replace1()
print(a)

>10

In this case, a changes only within the function.

al=[10]
def replace3():
    al=[15]
replace3()
print(al)

>[10]

Again, al changes only within the function.

al=[10]
def replace2():
    al[0]=15
replace2()
print(al)

>[15]

In this case, the value changed inside the function is also changing outside the function. ~~ This is because the list is a mutable object. ~~ It was a question of whether I was assigning to a local variable or referencing a global variable.

a=10
def replace1():
    global a
    a=15
replace1()
print(a)

>15

In the comment, it was pointed out that if you define a global variable, you can assign it. You can actually assign to a variable outside the function from inside the function. There seems to be a way to define it as a class variable. (See comments)

Verification of variable handling with recursive function

From here, we will try to handle variables with recursive functions. The recursive function used here counts how many times it can be calculated until 3-1 becomes 0.

ex1

count=0
a=3
def saiki1(a):
    if(a==0): return
    a=a-1
    count += 1
saiki1(a)
print(a, count)

>UnboundLocalError: local variable 'count' referenced before assignment

I tried it just in case, but an error occurs because count is not defined in the function. If you define `` `global count``` in the function, you will get the correct answer for count without an error.

ex2

count=0
a=3
def saiki2(a):
    count=0
    if(a==0): return
    a=a-1
    count += 1
saiki2(a)
print(a, count)

>2 1
>1 1
>0 1
>3 0

In this case, it changes inside the function, but outside the function it is the value originally defined. In this case, the answer is not correct because count = 0 is reset in the recursion. ex3

count=0
a=3
def saiki3(a, count):
    if(a==0): return
    a=a-1
    count += 1
    print(a, count)
    saiki3(a,count)
saiki3(a, count)
print(a, count)

>2 1
>1 2
>0 3
>3 0

If you add count to the argument of the recursive function, the answer is correct inside the function, but outside the function it is not received as a return value, so it is the value defined first. ex4

count=0
a=3
def saiki4(a, count):
    if(a==0): return a, count
    a=a-1
    count += 1
    print(a, count)
    saiki4(a, count)
    return a, count
a, count= saiki4(a, count)
print(a, count)

>2 1
>1 2
>0 3
>2 1

Next, when a and count are set as return values. In this case, it's complicated, but since we didn't receive a return value when we ran saiki4 on line 8, we're getting 21 of the first calculation in the function.

ex5 (legitimate)

count=0
a=3
def saiki5(a, count):
    if(a==0): return a, count
    a=a-1
    count += 1
    print(a, count)
    a,count= saiki5(a, count)
    return a, count
a, count= saiki5(a, count)
print(a, count)

>2 1
>1 2
>0 3
>0 3

In this case, since a and count are received in the function, the validity can be output. The same result can be obtained by writing `` `return saiki5 (a, count) ``` together on the 8th and 9th lines.

ex6 (legitimate)

count=[0]
a=3
def saiki6(a, count):
    if(a==0): return a
    a=a-1
    count[0] += 1
    print(a, count)
    a = saiki6(a, count)
    return a
a= saiki6(a, count)
print(a, count)

>2 [1]
>1 [2]
>0 [3]
>3 [3]

Finally, list count and check if only that element is rewritten. In this case, count is not the return value, but the value defined outside the function is rewritten inside the function. If you set `t = count [0] + 1 count = [t] ``` etc., the objects in the list will change, so 3 [0] `` will be output as the final result.

Postscript In the comments, I learned how to do it with global variables.

reference

https://excel-ubara.com/python/python016.html

Recommended Posts

A note on handling variables in Python recursive functions
A note on optimizing blackbox functions in Python
[python] Manage functions in a list
Using global variables in python functions
A note on touching Microsoft's face recognition API in Python
[Python3] Dynamically define global variables in functions
Note on encoding when LANG = C in Python
Practice applying functions and global variables in Python
Data analysis in Python: A note about line_profiler
A simple Pub / Sub program note in Python
Handling json in python
Hexadecimal handling in Python 3
Until drawing a 3D graph in Python on windows10
[Python] How to expand variables in a character string
Things to note when initializing a list in Python
Write a log-scale histogram on the x-axis in python
A note on speeding up Python code with Numba
Take a screenshot in Python
Create a function in Python
Create a dictionary in Python
Handle environment variables in Python
Python Input Note in AtCoder
Overriding library functions in Python
Handling of python on mac
Make a bookmarklet in Python
Draw a heart in Python
Relative url handling in python
Python functions learned in chemoinformatics
A note about [python] __debug__
A note on the default behavior of collate_fn in PyTorch
Create a list in Python with all followers on twitter
How to define multiple variables in a python for statement
A note on how to load a virtual environment in PyCharm
[GCP] A memorandum when running a Python program on Cloud Functions
[python] Manage functions in a dictionary (command table, function table, function pointer)
Building a Python environment on Mac
Maybe in a python (original title: Maybe in Python)
Write a binary search in Python
A note on what you did to use Flycheck with Python
Hit a command in Python (Windows)
[Note] Project Euler in Python (Problem 1-22)
Landmines hidden in Python class variables
Create a DI Container in Python
Building a Python environment on Ubuntu
A game to go on an adventure in python interactive mode
Python: A Note About Classes 1 "Abstract"
Easy! Implement a Twitter bot that runs on Heroku in Python
Create a Python environment on Mac (2017/4)
Draw a scatterplot matrix in python
A note about get_scorer in sklearn
ABC166 in Python A ~ C problem
Post a message from IBM Cloud Functions to Slack in Python
Write A * (A-star) algorithm in Python
Handling of JSON files in Python
Create a binary file in Python
Solve ABC036 A ~ C in Python
Create a python environment on centos
Write a pie chart in Python
Write a vim plugin in Python
Write a depth-first search in Python
Handling timezones in Python (datetime, pytz)