Why do I get “NameError: name '…' is not d

2019-09-21 18:10发布

问题:

filename:recom.py

# Returns a distance-based similarity score for person1 and person2
def sim_distance(prefs,person1,person2):
# Get the list of shared_items
    si={}
    for item in prefs[person1]:
        if item in prefs[person2]:
            si[item]=1
    # if they have no ratings in common, return 0
    if len(si)==0: return 0
    # Add up the squares of all the differences
    sum_of_squares=sum([pow(prefs[person1][item]-prefs[person2][item],2)
    for item in prefs[person1] if item in prefs[person2]])
    return 1/(1+sum_of_squares)

Am getting the error ,when i try to do reload(recom)

Traceback (most recent call last): File "", line 1, in NameError: name 'recom' is not defined

回答1:

I use python 3.4.3, and I just encountered the same problem. The below solution solved it for me.

When you use reload() you should also use from imp import reload before you use it.

As to getting the Euclidean Distance Score, you can get your answer like:

 from recom import critics
 from recom import sim_distance
 sim_distance(critics,'Lisa Rose','Gene Seymour')

The result is: 0.29429805508554946



回答2:

You need to have imported the module using "import recom" before it can be reloaded. Also, make sure the code is executing where it can resolve the path to recom.