-1

I am writing a piece of code for a homework class, which should allow me to calculate various distance statistics about two lists. However, when I assign the lists to the class, and try to print the result of one of the functions, I get the error,

NameError: name 'ratings1' is not defined

Leading me to believe that I did something incorrectly either in my __init__ function or the referencing in the functions. Can you help clarify what I'm doing wrong?

class similarity:

    def __init__(self, ratingX, ratingY):
        self.ratings1=ratingX
        self.ratings2=ratingY

    def minkowski(self,r):
        self.r=r
        mink=0
        length=len(ratings1)
        for i in range(0,length):
            mink=mink+(abs(ratings1[i]-ratings2[i]))**r
        mink=mink**(1/r)
        result='Given r=%d, Minkowski distance=%f'%(r,mink)
        return result             

    def pearson(self):
        Xavg=average(ratings1)
        Yavg=average(ratings2)
        n=len(ratings1)
        diffX=[]
        diffY=[]
        for i in range(0,n):
            diffX.append(ratings1[i]-Xavg)
            diffY.append(ratings2[i]-Yavg)
        return diffX
        diffXY=[]
        for i in range(0,n):
            diffXY.append(diffX[i]*diffY[i])

example2=similarity([1,3,5,5,6],[4,6,10,12,13])

print(example2.pearson())

Note: this error persists if I change the references to "ratings1/2" to "ratingsX/Y" in the functions.

Tadhg McDonald-Jensen
  • 20,699
  • 5
  • 35
  • 59

3 Answers3

0

You need to use self before every reference to instance variable, ie self.ratings1, and your indentation is wrong as well.

DeepSpace
  • 78,697
  • 11
  • 109
  • 154
  • The indentation was a result of me copy/pasting without checking the formatting, but the self.ratings1 solved my problem, thank you! – Nathan Wall Jun 10 '16 at 17:39
0

ratings are associated with class. Use self.ratings1 and so on..

SaurabhJinturkar
  • 554
  • 7
  • 20
0

I just figured out my mistake. For each function I failed to use the self. phrase before the ratings name. To amend this, I added

ratings1=self.
ratings2=self.ratings2

To the beginning of each function. Problem solved.