Reputation: 489
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):
n=len(v1);
v1=numpy.asarray(v1)
v2=numpy.zeros(k)
v2=numpy.asarray(v2,int)
if k>n:
self.trigger1()
else:
l=0;
while (l<k):
best_now=numpy.asarray(numpy.where(v1==max(v1)),int)[0,0]
v2[l]=best_now;
v1[best_now]=0
'v1=numpy.delete(v1, best_now)'
'print l,v2;'
l=l+1;
return v2
def trigger1(self):
tkMessageBox.showwarning('Wrong value','Select the correct value')
var1=numpy.asarray(numpy.random.randint(0,100,10));
var2=var1
var3=numpy.asarray([1,2,3,3,3,3,3,4,5,6,7,8,9])
elite=kbest().val_report(3, var1);
print elite
print var2
Upvotes: 0
Views: 311
Reputation: 61124
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])
Upvotes: 4