Take the 2-minute tour ×

I wrote this function (used later to select elite species in the genetic algorithm) to select k best values out of n, where not all n values are unique. First of all, I'd massively appreciate any comments to the code, but I'm primarily concerned with the fact that for some reason values in second vector (var2) are also set to 0. If instead of array I use list, this doesn't happen, but of course I want to use arrays rather than lists! So any comments are very welcome

import numpy

import tkMessageBox

'v1 is the vector of values from which k best must be selected for maximization problems'

class kbest():

    def val_report(self,k,v1):
        if k>n:
            while (l<k):
                'v1=numpy.delete(v1, best_now)'
                'print l,v2;'
        return v2

    def trigger1(self):
        tkMessageBox.showwarning('Wrong value','Select the correct value')




elite=kbest().val_report(3, var1);   

print elite

print var2
share|improve this question
Format your code. –  Emil Lundberg Dec 16 '11 at 0:13
There's a lot of unnecessary stuff in here. I hope someone else will answer your question, but many people (such as myself) aren't going to read something that has unnecessary complexity such as GUI code that has nothing to do with your question or commented out lines. Coding according to regular Python standards would also make this more useful. See PEP 8. –  Michael Hoffman Dec 16 '11 at 0:18
sorted(v1)[-k:] –  yurib Dec 16 '11 at 0:28
Much of val_report (the second through fourth lines and everything in the else block) can be replaced with v2 = numpy.argsort(v1)[-k:][::-1]. –  David Alber Dec 16 '11 at 0:40

1 Answer 1

up vote 4 down vote accepted

You are just giving var1 the alias var2. They both point to the same content.

You must copy the content over to a new object.

In [1]: x = numpy.arange(5)

In [2]: x
Out[2]: array([0, 1, 2, 3, 4])

In [3]: y = x.copy()

In [4]: x[:] = 0

In [5]: x
Out[5]: array([0, 0, 0, 0, 0])

In [6]: y
Out[6]: array([0, 1, 2, 3, 4])
share|improve this answer
The terminology here is a bit wonky, but this is exactly the issue. –  Karl Knechtel Dec 16 '11 at 2:29

Your Answer


