0

This is my code:

def getGraphWave(G, d, maxk, p):
    data = dict()
    output_wavelets = {2:33,5:77,...}
    print(len(output_wavelets)) 
    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 = []
    print(len(output_wavelets))
    for i in range(k):
        Seed = max(output_wavelets, key=output_wavelets.get)
        S.append(Seed)
        output_wavelets.pop(Seed)
    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?

Z Mario
  • 63
  • 4
  • 12
  • example input and example output please? – Netwave Apr 29 '19 at 08:55
  • https://stackoverflow.com/a/21700609/173314 gives a very long explanation of what's happening here. The short version is that `graphwave()` is passed the `output_wavelets` list itself, not a copy of it, so when you call `output_wavelets.pop(Seed)` you are modifying the list. – wjt Apr 29 '19 at 09:05
  • I use `ow = deepcopy(output_wavelets) S = graphwave(i, ow)` to solve this problem. But I don`t know why. – Z Mario Apr 29 '19 at 09:06

2 Answers2

1

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.

0

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)

Sanch
  • 137
  • 7