我正在编写一个函数来计算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有一个只写型内存管理系统,所以当我创建许多重复列表时(这个函数肯定会),这些重复的对象都指向同一个项目,只要它们不是改性。这似乎上面应该不是那么糟糕......