0

I was working on the LeetCode problem Graph Valid Tree (#261) and was having some weird issue with Python when using global variables to detect a cycle. Essentially, if I detected a cycle, I wanted to set boolCycle to True. However, sometimes, I would print boolCycle out during the DFS (where it would evaluate to True), and then after running DFS and it would evaluate to False. I couldn't figure out why this is happening as boolCycle is a global variable, and the only change I ever make to it is to set it to True, so it should remain that way.

I instead came up with a hacky solution where I just created a list called cycle and added an element to it if there was a cycle, which ended up working. I'm curious as to why modifying the global list works as intended but modifying the global boolean doesn't.

cycle = []
boolCycle = False
def dfs(parent, node):
    visited.add(node)
    for neighbor in graph[node]:
        if neighbor in visited and neighbor != parent:
            cycle.append('hello')
            boolCycle = True
            return
        if neighbor not in visited:
            dfs(node, neighbor)
martineau
  • 119,623
  • 25
  • 170
  • 301

1 Answers1

1

After

def dfs(parent, node):

add

    global boolCycle
Dave W. Smith
  • 24,318
  • 4
  • 40
  • 46
  • 1
    Exactly. Note that this is only needed because `boolCycle` is being **assigned to**, not merely accessed. When you assign to a variable in a function, Python will assume that the variable is local unless you explicitly specify otherwise. – Daniel Walker May 11 '22 at 02:59