0

I have defined the following function with Python:

def step(G,V1,V2):
    tempcut=sys.maxint
    for k in range(min(len(V1),len(V2))):
        V1, V2, C=Switch(G,V1,V2,k)
        print(C)
        if C<tempcut:
           tempcut=C
           best1=V1
           best2=V2
           print('enter')
           print(tempcut)
           print(best1)  
           print(best2)      
    return best1, best2, tempcut,  

G is a graph object (with networkx), V1 and V2 are two lists (a partition of the nodes of G). The function Switch(, , ) is another function that I've defined previously which returns an update of V1 and V2 and moreover an integer C.

My purpose is to return the lists best1, best2 and the smallest value of tempcut. The function returns the correct value of tempcut but on the other hand it returns the last values of V1 and V2, but not best1 and best2.

user3666197
  • 1
  • 6
  • 50
  • 92
manifold
  • 233
  • 2
  • 9

2 Answers2

1

You should copy your list. You are changing it by reference. Check the official Python FAQ, Thread

Try:

import copy

def step(G,V1,V2):
    tempcut=sys.maxint
    for k in range(min(len(V1),len(V2))):
        V1, V2, C=Switch(G,V1,V2,k)
        print(C)
        if C<tempcut:
           tempcut=C
           best1=copy.copy(V1) #or : best1= V1[:] as Serge suggested  
           best2=copy.copy(V2) #or : best2= V2[:] as Serge suggested  
           print('enter')
           print(tempcut)
           print(best1)  
           print(best2)      
    return best1, best2, tempcut, 
Community
  • 1
  • 1
0

A safer construct may do this:

import copy                                 # use copy as Taha proposed
def step( G, V1, V2 ):
    tempcut = sys.maxint
    best1   = []                            # init for a case if() would never come true
    best2   = []                            # init for a case if() would never come true
    for k in range( min( len( V1 ), len( V2 ) ) ):
        V1, V2, C = Switch( G, V1, V2, k )
        print( C )
        if C < tempcut:
           tempcut = C
           best1   = copy.copy( V1 )        # use copy as Taha proposed
           best2   = copy.copy( V2 )        # use copy as Taha proposed
           print( 'enter' )
           print( tempcut )
           print( best1 )
           print( best2 )
    return ( best1, best2, tempcut,  )      # return as tuple
user3666197
  • 1
  • 6
  • 50
  • 92