global vs nonlocal

whitehousechef·2024년 10월 22일

using nonlocal

When the function is nested inside another function

def solution():
    count = 0  # Enclosing variable

    def dfs():
        nonlocal count  # Declare count as nonlocal to modify it
        count += 1

    dfs()  # Call dfs to increment count
    print(count)  # Output: 1

solution()

global

when it is not enclosed in another function

choices = [1,3,4]
n=5
count = 0
def dfs(cur_sum):
    global count,n
    if cur_sum==n:
        count+=1
        return
    elif cur_sum>n:
        return
    for choice in choices:
        cur_sum+=choice
        # if cur_sum<n:
        dfs(cur_sum)
        cur_sum-=choice
dfs(0)

print(count)

0개의 댓글