1

I am continuously getting NameError: name 'max_col' is not defined. After some research I realized that if I wanted to use max_col inside a function as a global variable I had to declare it that way. However, even after that modification, it seems not to work.

After banging my head for over an hour I put the variable max_col inside an array, popped it inside explore_color and and then used max. For some funny reason that seemed to work. Does someone know what I am missing here. Why can't I use the max function in a global variable?

def max_area(grid):

     max_col = float('-inf')

     def explore_color(color, row, col, size):

         grid[row][col] = float('inf')  
         global max_col
         max_col = max(max_col, size)

         directions = [(-1,0), (1,0), (0,1), (0,-1)]
         for dir in directions:
           next_x, next_y = row + dir[0], col + dir[1]
           if next_x >= 0 and next_x < len(grid) and next_y >= 0 and next_y < len(grid[0]) and grid[next_x][next_y] == color:
              explore_color(color, next_x, next_y, size + 1)

     for row in range(len(arr)):
        for col in range(len(arr[0])):
           if grid[row][col] != float('inf'):
             explore_color(grid[row][col], row, col, 1)

1 Answers1

3

global does not work here, because max_col is not in the global scope; it is just "one scope up". Try nonlocal instead (Python 3 only). Minimal example:

def outer():
    foo = 1
    def inner():
        nonlocal foo
        foo = max(foo, 10)
        print("in inner", foo)
    inner()
    print("in outer", foo)
outer()

This prints 10 both times.

Also see here for more information and examples.

tobias_k
  • 81,265
  • 12
  • 120
  • 179