gpt4 book ai didi

python - 在Python函数中使用全局变量

转载 作者:行者123 更新时间:2023-12-01 04:12:13 25 4
gpt4 key购买 nike

我正在浏览this最长递增子序列问题的解决方案,并注意到子序列长度最大值的全局变量在运行主函数的驱动程序以及计算最长子序列的实际函数中都被重新定义:

# global variable to store the maximum
global maximum

def _lis(arr , n ):

# to allow the access of global variable
global maximum

# Base Case
if n == 1 :
return 1

# maxEndingHere is the length of LIS ending with arr[n-1]
maxEndingHere = 1

"""Recursively get all LIS ending with arr[0], arr[1]..arr[n-2]
IF arr[n-1] is maller than arr[n-1], and max ending with
arr[n-1] needs to be updated, then update it"""

for i in xrange(1, n):
res = _lis(arr , i)
if arr[i-1] < arr[n-1] and res+1 > maxEndingHere:
maxEndingHere = res +1

# Compare maxEndingHere with overall maximum.And update
# the overall maximum if needed
maximum = max(maximum , maxEndingHere)

return maxEndingHere

def lis(arr):

# to allow the access of global variable
global maximum

# lenght of arr
n = len(arr)

# maximum variable holds the result
maximum = 1

# The function _lis() stores its result in maximum
_lis(arr , n)

return maximum

似乎每次进行递归调用时,最大值都会被重置。在函数的局部范围内重新定义全局变量的目的是什么?

最佳答案

您必须在函数中使用global关键字才能全局更改变量;如果不使用该关键字,它将创建一个具有相同名称的局部范围变量。语句全局最大值不会“重新定义”变量,但它告诉Python,如果在此函数中maximum设置为某个值,则全局变量意味着改变。

In [1]: a = 42

In [2]: def f():
...: a = 23
...:

In [3]: f()

In [4]: a
Out[4]: 42

In [5]: def g():
...: global a
...: a = 23
...:

In [6]: g()

In [7]: a
Out[7]: 23

关于python - 在Python函数中使用全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34776426/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com