0

I am trying to solve a Python challenge and my codes probably do not work correctly yet, but I am puzzled that the same function when called at different points of the codes return different values with the same parameters. My guess is that calling the function with certain parameters make it work differently from before, but is that even possible? Thanks for any clues to this.

def connectedNodes(graph,start,last=0,group=set()):
  group.add(start)
  if len(graph[start])==1: #end
    return group
  else:
    for node in graph[start]:
      if node!=last:
        newgroup = connectedNodes(graph,node,start,group)
        group = group.union(newgroup)
    return group
  return None

graph = {1: [5], 4: [5], 3: [5], 5: [1, 4, 3, 2], 2: [5, 15, 7], 7: [2, 8], 8: [7, 38], 15: [2], 38: [8]}
print(connectedNodes(graph,7,2))#returns {38, 7, 8} here
for city in graph:
  for node in graph[city]:
    print(node, city, connectedNodes(graph,node,city))
print(connectedNodes(graph,7,2))#returns {1, 2, 3, 4, 5, 38, 7, 8, 15}
  • 1
    You're modifying the `group` set each time you call the function, and that's being saved. – Barmar Jan 13 '22 at 06:47

0 Answers0