0

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]))
kulssaka
  • 226
  • 8
  • 27
  • Possible duplicate of [How can I build a recursive function in python?](http://stackoverflow.com/questions/479343/how-can-i-build-a-recursive-function-in-python) – kulssaka Feb 02 '17 at 14:21

2 Answers2

4

Place a return before your recursive calls to cpRec.

Jean Hominal
  • 16,518
  • 5
  • 56
  • 90
2

Try adding 'return' statement to those two recursive cpRec calls:

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:
        return cpRec(L, Lc, chiffre, cpt+ 1)
    else:
        Lc += [cpt]
        return cpRec(L, Lc, first, 1)
jcdenton
  • 361
  • 2
  • 10