1

I'm going through this solution for the Longest Increasing Subsequence problem and noticed that the global variable for the maximum value of the sub sequence length is being redefined both in the driver that runs the main function as well as in the actual function that computes the longest sub sequence:

# 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

It would seem that each time a recursive call is made, the maximum value would be reset. What would be the purpose of redefining the global variables within the local scope of the functions?

5
  • That value should just be passed into the method... Maybe coding style? I think that is bad practice though. I lean toward if you are using a global variable you're probably doing it wrong... Commented Jan 13, 2016 at 20:31
  • Are you expecting global to reset the value of the global variable? I don't see anything I'd describe as "resetting" the maximum in _lis. Commented Jan 13, 2016 at 20:40
  • @user2357112, look just above the return. Commented Jan 13, 2016 at 20:43
  • @Prune: I wouldn't describe that as "resetting" the maximum. Commented Jan 13, 2016 at 20:45
  • A good example, why global makes code less understandable. Commented Jan 13, 2016 at 20:47

2 Answers 2

1

You have to use the global keyword in a function to be able to change the variable globally; if you do not use the keyword, it will create a variable of local scope with the same name. The statement global maximum does not “re-define” the variable, but it tells Python that if in this function maximum is set to some value, the global variable is meant to change.

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
Sign up to request clarification or add additional context in comments.

4 Comments

The question is on the definition (value) of the variable, not its declaration.
I think that the person who asked the question misinterpreted the global keyword as “defining” something and that the question is actually about the use of the global keyword.
I wasn't the one who downvoted this, and I wouldn't have because this response directly answers the question. Also, when I first learned python, I was taught that the use of global variables should be avoided. How could the code for these functions be structured such that a global variable isn't used?
You could change _lis() so that it accepts the parameter maximum and returns two values: the value it is returning already plus the current maximum value. Then you do not need a global variable. The code could look like this: gist.github.com/gandaro/8e9d146fadc69eed00b2
1

Look at the code structure: there is no recursive call to lis; when it initializes maximum = 1 at line 42, that's the only time this statement is executed. Everything else is done within _lis, where the maximum is only updated, never reset to 1.

I recommend that you find other code to study. This example shows bad habits in handling the variables maximum and arr -- the author ignores the power of recursion here, using loop-style logic. You could make a nice class exercise out of upgrading this to a program easy to read and maintain.


In dynamic programming, the only global variables should be for memoization. In fact, this example uses no memoization -- which means it is not dynamic programming. In short, there should be a memo list, where memo[n] holds the value from _lis(arr, n). Recursive calls should not go farther than one level deep, as _lis will return this stored value. The answer at the end is simply max(memo).

See the WIkipedia pages on dynamic programming and memoization.

2 Comments

I think the for loop is required in the top down approach for dynamic programming. How would you solve the problem without the for loop and how would you update the maximum variable?
It's not so much the existing for loop; it's the approach of the recursion. maximum is an ugly clart in this respect, as is the static use of arr -- it's never changed from one call to the next, which tastes like another global variable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.