Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NameError: global name 'operator' is not defined

import KNN
def c(i,d,l,k):
    dss=d.shape[0]
    dm=tile(i,(dss,1))-d
    sqm=dm**2
    sqd=sqm.sum(axis=1)
    dist=sqd**0.5
    sDI=dist.argsort()
    clc={}
    for i in range(k):
        vl=l[sDI[i]]
        clc[vl]=clc.get(vl,0)+1     
    sCC=sorted(clc.items(),key=operator.itemgetter(1),reverse=True)
    return sCC[0][0]

c([0,0],g,l,3)

Error:

Traceback (most recent call last):
  File "<pyshell#32>", line 1, in <module>
    c([0,0],g,l,3)
  File "<pyshell#31>", line 12, in c
    sCC=sorted(clc.items(),key=operator.itemgetter(1),reverse=True)
NameError: global name 'operator' is not defined

KNN contains the following code:

from numpy import *
import operator

def createDataSet():
    group = array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])
    labels = ['A','A','B','B']
    return group, labels

Why is there a error as mentioned above? Program is run on Python 3.3.2. This code is a simple k-classification algorithm run in Python.

like image 892
tcp Avatar asked Nov 30 '22 20:11

tcp


1 Answers

You need to import operator into the local namespace; import KNN will not also import the submodules it imports.

As a rule, you need to be explicit about any and all modules and objects you use, with the exception of the builtins (https://docs.python.org/2/library/functions.html).

Unlike some other languages, there are no implicit imports.

Advanced tip/editorial on imports: You might be tempted to use KNN.operator. It's available there because it was imported by KNN. However, this is almost always a regrettable decision, as confuses the picture: Is this a special module? If so what's its interface? Save the cuteness, be explicit.

like image 52
Nino Walker Avatar answered Dec 04 '22 09:12

Nino Walker