0

I am trying to get the following recursive function to work. It is supposed to find the biggest list of vectors in vspace(n) such that all the vectors are at least distance d from each other. My current issue is that the variable sol does not seem to be behaving locally. For some reason when the code shifts back to earlier iterations, the variable sol does not revert back to what it was in that iteration of bestCode. Any ideas?

rlist is a function that reduced a list of vectors by removing any that are too close to x (less than distance d).

def bestCode(n, d, sol):   
    best=[]
    v = vspace(n)
    for i in range(0, len(sol)):
        v = rlist(sol[i], v, d)
    if(len(v) != 0):
        for i in range(0, len(v)):
                sol2 = sol
                sol2.append(v[i])
                sol2 = bestCode(n, d, sol2)
            if(len(sol2)>len(best)):
                best = sol2
        return best
    else:
        return sol
SeanBallentine
  • 173
  • 1
  • 2
  • 8
  • 3
    Aside: `for i in range(0, len(v)): v[i]` is a long, error-prone way of writing `for element in v: element`. – Two-Bit Alchemist Nov 13 '15 at 18:26
  • Can you fix the indentation so this code will actually work? – Two-Bit Alchemist Nov 13 '15 at 18:28
  • Possible duplicate of [How do I pass a variable by reference?](http://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference) – Kevin Nov 13 '15 at 18:29
  • 1
    `sol2 = sol` creates a new reference to the list referenced by `sol`. If you want `sol2` to be a new list so that operations on `sol2` don't change the original list, you should copy `sol2 = sol[:]`. – tdelaney Nov 13 '15 at 18:50
  • THATS IT @tdelaney THANKS! If you put in an answer I can accept it – SeanBallentine Nov 13 '15 at 19:25
  • @SeanBallentine The comment above has been converted into an answer by its author which I encourage you to accept. Glad your problem is solved. – Two-Bit Alchemist Nov 13 '15 at 22:32

1 Answers1

2

Python variables are references to objects. Assignment such as sol2 = sol just creates a new reference to the object. For mutable objects like lists, changes to sol2 are seen by sol because they both reference the same list. If you want sol2 to be independent, you need to copy. For lists, the normal way to do that is sol2 = sol[:].

tdelaney
  • 73,364
  • 6
  • 83
  • 116