title: Convert a recursive function into Non recursive in Python
body: <p>How could I convert and optimize this recursive function into an iterative one. I'm trying to program a function that accumulates the flow using a map of directions, however, for direction maps of very large size the function just crashes. I am programming in Python, and increasing the system recursion limit is not an option.</p>
  
  <pre><code>def AcumulacionCelda(x,y):
              if Acum[x,y]==NoData:
                  Acum[x,y]=1
                  for m, n in product(range(-1,2), range(-1,2)):
                      if m==-1 and n==-1 and Direcciones[x+m,y+n]==4:
                          AcumulacionCelda(x+m,y+n)
                          Acum[x,y]=Acum[x,y]+Acum[x+m,y+n]
                      elif m==-1 and n==0 and Direcciones[x+m,y+n]==5:
                          AcumulacionCelda(x+m,y+n)
                          Acum[x,y]=Acum[x,y]+Acum[x+m,y+n]
                      elif m==-1 and n==1 and Direcciones[x+m,y+n]==6:
                          AcumulacionCelda(x+m,y+n)
                          Acum[x,y]=Acum[x,y]+Acum[x+m,y+n]
                      elif m==0 and n==1 and Direcciones[x+m,y+n]==7:
                          AcumulacionCelda(x+m,y+n)
                          Acum[x,y]=Acum[x,y]+Acum[x+m,y+n]
                      elif m==1 and n==1 and Direcciones[x+m,y+n]==8:
                          AcumulacionCelda(x+m,y+n)
                          Acum[x,y]=Acum[x,y]+Acum[x+m,y+n]
                      elif m==1 and n==0 and Direcciones[x+m,y+n]==1:
                          AcumulacionCelda(x+m,y+n)
                          Acum[x,y]=Acum[x,y]+Acum[x+m,y+n]
                      elif m==1 and n==-1 and Direcciones[x+m,y+n]==2:
                          AcumulacionCelda(x+m,y+n)
                          Acum[x,y]=Acum[x,y]+Acum[x+m,y+n]
                      elif m==0 and n==-1 and Direcciones[x+m,y+n]==3:
                          AcumulacionCelda(x+m,y+n)
                          Acum[x,y]=Acum[x,y]+Acum[x+m,y+n]
  
              return;
  
  for i, j in product(range(1,Filas-1), range(1,Columnas-1)):
        AcumulacionCelda(i,j)
  </code></pre>