如何在递归函数中管理内存,每次递归函数调用都会创建新列表?

时间:2015-07-20 15:08:54

标签: python list-comprehension

我正在编写一个函数来计算M网格中N-dimensions长度X_n的可能路径,从列表D_n中指定的点开始,其中网格的维度在列表中给出Solve

我将网格的当前坐标和尺寸传递给lists函数def Solve(X_n, D_n, M): """Find number of paths of length M in grid of dimensions D_n we can get starting at X_n""" #using dynamic methods to avoid unnecessary calculations by storing number of paths # from a given grid member that are available. This will be 2^N except for edge cases if M == 1: return solve_grid[tuple(X_n)] if solve_grid[tuple(X_n)] else count_em(X_n, D_n) #identify which current coordinates are at an edge and don't modify these in wrong direction diff = np.subtract(D_n, X_n) good_add = [i for i, d in enumerate(diff) if d!= 0] good_subtract = [i for i, x in enumerate(X_n) if x != 0] return_val = 0 #here's my concern: what's going to happen with all these lists? #is there a better way to handle this? for idx in good_add: new_x = list(X_n) new_x[idx] += 1 return_val += Solve(new_x, D_n, M-1) for idx in good_subtract: new_x = list(X_n) new_x[idx] -= 1 return_val += Solve(new_x, D_n, M-1) return return_val 。但是,这意味着我正在制作许多列表副本,如下所示。

f(*args)

我的理解是Python有一个只写型内存管理系统,所以当我创建许多重复列表时(这个函数肯定会),这些重复的对象都指向同一个项目,只要它们不是改性。这似乎上面应该不是那么糟糕......

  1. 这是好记忆还是会爆炸?
  2. 如果它会爆炸,用列表做一个聪明的方法(它们是如此方便)?
  3. 如果没有,使用{{1}}样式函数是递归传递坐标和尺寸的最佳方法吗?

0 个答案:

没有答案