1

I have the following code where I am trying to generate graphs given certain parameters:

def generate_graph(numNodes, equality, magnitude, conectivity):
    graph = {}
    nodes = []
    for x in range(numNodes):
        graph[x] = {}
        nodes.append(x)
    nodes2 = nodes

    for i in range(len(nodes)):
        nextNodes = nodes2
        print(nextNodes)
        nextNodes.remove(i)
        for j in range(conectivity):
            chosenNode = random.choice(nextNodes)
            nextNodes.remove(chosenNode)
            connected = False
            for node in graph[chosenNode]:
                if node == i:
                    connected = True

            if not connected:
                graph[i][chosenNode] = random.randint(0, magnitude)

    return graph

The issue that I am having is to do with this area right here :

nextNodes = nodes2
print(nextNodes)

As the nodes2 array is declared before in a for loop and is not changed at any other point in the rest of this function I assumed that nextNodes will always print the same. The original nodes2, that is. However somehow it seems that it is not and instead some values are no longer there. The results i get are like the following:

generate_graph(10, 0, 10, 4)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[4, 5, 6, 7, 9]
...and then an error after the second iteration

Due to this I always get an error where I am trying to remove a variable that does not exist.

Is there anyway that the reassigment of the variable can cause the orignal list to be overwritten? Am I over looking some fundemental flaw in my approach?.

martineau
  • 119,623
  • 25
  • 170
  • 301
  • 4
    The `nextNodes = nodes2` doesn't create a copy of `nodes2`, it just gives the list another name. If you want an independent copy use ``nextNodes = nodes2.copy()`. – martineau Sep 28 '20 at 17:00
  • Just adding to the above comment. You should take a look at mutable and immutable objects in python. Lists are mutable, thats why it does not create a copy but just a "reference" to the same object. If you want an immutable structure you should use a tuple instead of a list – Felipe Emerim Sep 28 '20 at 17:07

0 Answers0