I am starting python and I have a little problem with the return in python. So, the final value of Lc, my result list is correct in my recursive function cpRec, but when it returns it, I get None in the function cp2. I can use a global value for Lc, and the problem is solved, but it's ugly... So is there an other way to do it ?
def cpRec(L, Lc, chiffre,cpt):
if len(L) == 0:
Lc += [cpt]
#print Lc <- if I print here, the result is good.
return Lc
else:
first = L.pop(0)
if first == chiffre:
cpRec(L, Lc, chiffre, cpt+ 1)
else:
Lc += [cpt]
cpRec(L, Lc, first, 1)
def cp2(L):
Lc =[L[0]]
return cpRec(L,Lc, L[0], 0)
print(cp2([0,1,1,1,0,0,1,1,1])) #<- print None instead of Lc
Using the global like this is working but it's ugly:
def cpRec(L,chiffre,cpt):
global Lc
if len(L) == 0:
Lc += [cpt]
else:
first = L.pop(0)
if first == chiffre:
cpRec(L, chiffre, cpt+ 1)
else:
Lc += [cpt]
cpRec(L,first, 1)
def cp2(L):
global Lc
Lc =[L[0]]
cpRec(L, L[0], 0)
return Lc
print(cp2([0,1,1,1,0,0,1,1,1]))