This is my code:

def getGraphWave(G, d, maxk, p):
    data = dict()
    output_wavelets = {2:33,5:77,...}
    k = [10,20]  
    for i in k:
        S = graphwave(i, output_wavelets)
        # size = avgSize(G, S, p, 200)
        size = IC(d, S, p)
        data[i] = size + i
    return data

The output_wavelets is a dict and the length of it is 2000. However, when running the following code:

def graphwave(k, output_wavelets):
    S = []
    for i in range(k):
        Seed = max(output_wavelets, key=output_wavelets.get)
    return S

In the getGraphWave(G,D,maxk,p), graphWave(k,output_wavelets) runs two times in the circulation. However, Why in the graphWave(), the result of print(len(output_wavelets)) is 2000 and 1991?
I thought output_wavelets is not changed before output_wavelets. And how to let output_wavelets always be the original?

2 Answers

Tomcat Engineering On Best Solutions

When you call graphwave(i, output_wavelets) this passes a reference to output_wavelets into the function, not a copy of output_wavelets. This means that when the function modifies the output_wavelets dictionary it is modifying the original dictionary.

The output_wavelets.pop(Seed) line removes items from the dictionary, so is modifying the output_wavelets dictionary that you passed in. That is why it is getting smaller!

There are various ways which you could fix this. The simplest (but probably not the most efficient) would be to use the copy.copy() function to make a copy of your dictionary at the start of the graphwave function, and edit the copy rather than the original.

Sanch On

First you need to understand how value pass in python. Actually it depend on param which you passing to function. like if you pass list, dict or any mutable object.. it can modify within the function. but if you pass tuple, string or any immutable object.. it will not change.

In your case you can copy existing dict and then modify it. like

temp_output_wavelets = copy.deepcopy(output_wavelets)