Here is a recursive R function involving a matrix S from the parent environment:
f <- function(m, k, n) { if(n == 0) { return(100) } if(m == 1) { return(0) } if(!is.na(S[m, n])) { return(S[m, n]) } s <- f(m-1, 1, n) i <- k while(i <= 5) { if(n > 2) { s <- s + f(m, i, n-1) } else { s <- s + f(m-1, 1, n-1) } i <- i + 1 } if(k == 1) { S[m, n] <- s } return(s)}Here is the result of a call to this function:
> n <- 4> S <- matrix(NA_real_, nrow = n, ncol = n)> f(n, 1, n)[1] 127500Now, here is the Python version:
import numpy as npdef f(m, k, n): if n == 0: return 100 if m == 1: return 0 if S[m-1, n-1] is not None: return S[m-1, n-1] s = f(m-1, 1, n) i = k while i <= 5: if n > 2: s = s + f(m, i, n-1) else: s = s + f(m-1, 1, n-1) i = i + 1 if k == 1: S[m-1, n-1] = s return sThe call:
>>> n = 4>>> S = np.full((n, n), None)>>> f(n, 1, n)312500The Python result is different from the R result. Why?
One gets identical results if one replaces
if S[m-1, n-1] is not None: return S[m-1, n-1]with
if k == 1 and S[m-1, n-1] is not None: return S[m-1, n-1]I also have a C++ version of this function, and it has the same behavior as the R function.