This one's the program to calculate the frequency in an array. Here I'am getting the error that global name "mod" is not defined. Look at:: tempr=mod(self.a[i]) , where I am using it and the function mod has been written in a different function. Please help me in correcting this function.
class abc:
def __init__(self):
self.n=0
self.a=[]
def read(self):
self.n=input()
for i in range(0,self.n):
temp=input()
self.a.append(temp)
def freq(self):
max=self.a[0]
for i in range(0,self.n):
tempr=mod(self.a[i])
if tempr>max:
max=tempr
tempa=[0]*(2*(max)+1)
bb=[0]*self.n
for j in range(0,self.n):
if(self.a[j]>=0):
tempa[self.a[j]]=tempa[self.a[j]]+1
else:
tempa[max-self.a[j]]=tempa[max-self.a[j]]+1
for i in range(0,self.n):
if bb[self.a[i]]==0:
if self.a[i]>=0:
print "%d : %d " % (self.a[i],tempa[self.a[i]])
bb[self.a[i]]=bb[self.a[i]]+1
else:
print "%d : %d " % (self.a[i],tempa[max-self.a[i]])
bb[self.a[i]]=bb[self.a[i]]+1
def mod(y):
if y>=0:
return y
else:
return y
k=abc()
k.read()
k.freq()
1 Answer 1
There are two issues in your code:
It seems that you want your
modto be a static method. Non-static method should always haveselfas a first argument.Even if
modis a static method, you need to call it asabc.mod.
Two ways to solve it:
- Make
moda global function instead of a method (just indent its definition 4 spaces to the left)
or
- Make it a static method by prepending it with
@staticmethodand call it asabc.mod:
...
tempr=abc.mod(self.a[i])
...
@staticmethod
def mod(y):
if y>=0:
return y
else:
return y
Also note that mod should probably return -y if y < 0
mod(y)always returnsy. Doesn't seem very useful to me....