0
from math import sqrt
def sim_distance(prefs,person1,person2):
     si={}
     for item in prefs[person1]:
          if item in prefs[person2]:
               si[item]=1
     if len(si)==0: return 0
     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+sqrt(sum_of_squares))

reload(recommendations)
recommendations.sim_distance(critics,'Lisa Rose','Gene Seymour')

And it's error

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    recommendations.sim_distance(critics,'Lisa Rose','Gene Seymour')
NameError: name 'critics' is not defined

critics is a custom array

jamylak
  • 128,818
  • 30
  • 231
  • 230
MindHacks
  • 931
  • 2
  • 7
  • 9
  • Where are you initializing `critics`? – valdarin Apr 14 '12 at 16:17
  • in the recommendations.py,before sim_distance – MindHacks Apr 14 '12 at 16:23
  • If you can include the code that initializes critics I think we can figure out where the trouble is. As noted already below the interpreter is telling you that it does not have anything named `critics` in the current scope. I am guessing you are defining it within a function which means once the function returns it is no longer in the scope. – valdarin Apr 14 '12 at 16:27
  • Yes,it's the scope issue, i define critics in the global scope outside the function and then it work out.But if i want use critics next time, i must initialize it every time? Whether there is a more simple definition method, such as saving in a file so that I could call it. – MindHacks Apr 14 '12 at 16:59
  • @Andrew Barrett:It is so complex that I can't read now.Anyway thank you. – MindHacks Apr 14 '12 at 17:02
  • If you want to save a set of data and retrieve it each time your program runs I would recommend a file or database. For simple data sets python provides the `pickle` function [pickle](http://docs.python.org/library/pickle.html) which allows you to save and retrieve a python data structure using a file. – valdarin Apr 14 '12 at 17:04

2 Answers2

1

This doesn't have anything to do with reloading namespaces. You simply haven't defined critics.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
0

This looks like it's probably a scope issue. If you are defining critics within a different function then critics will only exist within that function. You are referencing critics in the main scope of the function here so you will need to either return critics from the function that creates it or (not as ideal) define it initially within the global scope.

def initCritics():
    critics = []
    # make some critics

    return critics

critics = initCritics()

recommendations.sim_distance(critics,'Lisa Rose','Gene Seymour')
valdarin
  • 921
  • 10
  • 20