I have the following function-in-function definition (see below).
When I ran >>> pd = distrib(10,listAll) I get this (note the line number correspond to the lines in my file not in the sample below)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "transportOpt.py", line 78, in distrib
N = NN(0,t1)
File "transportOpt.py", line 48, in NN
print(p1,p2)
NameError: global name 'p1' is not defined
The function itself
def distrib(Nm,lf):
l = len(lf)
pd = {}# the output dictionary distribution
sumpd = 0# the total number of samples
p1=0
p2=0
buf=[lf[0]]
def NN(a,b):
global p1,p2
print(p1,p2)
y = max(a,b)
x = min(a,b)
if y>p2:
for j in range(p2-p1+1,y-p1+1):
buf.append(buf[j-1]+lf[j])
p2 = y
if x>p1:
for j in range(0,x-p1):
buf.pull(j)
p1 = x
return buf[b-p1]-buf[a-p1]
def UpdateDistrib(a,b):
global sumpd
tao = t1-t0
if tao < 0:
print('UpdateDistrib: t1<t0: mistake')
if tao == 0:
tao = 1
CurrentCount = pd.get(tao,0)
pd[tao] = CurrentCount + 1.
sumpd = sumpd + 1.
def normdistrib():
for i in pd.keys():
num = pd[i]
pd[i] = num/sumpd
for t1 in range(l):
N = NN(0,t1)
if N>Nm:
UpdateDistrib(0,t1)
break
if t1==l-1 and N<=Nm:
normdistrib()
return pd
for t0 in range(1,l):
N = NN(t0,t1)
if N<=Nm:
if t1==l-1:
normdistrib()
return pd
r = range(t1+1,l)
for t1 in r:
N = NN(t0,t1)
if N>Nm:
UpdateDistrib(t0,t1)
break
else:
UpdateDistrib(t0,t1)
normdistrib()
return pd
What's wrong? Do I use "global" in the wrong way?