I am using the following code to generate a two dimensional list.
grid = [[ 1 if i == 0 or j == 0 else 0 for i in range(size) ] for j in range(size)]
which generates
[1, 1, 1]
[1, 0, 0]
[1, 0, 0]
Is it possible to use the values to get the next values inside list comp like
grid[1][1] = grid[0][1] + grid[1][0]
so it will look like
[1, 1, 1]
[1, 2, 3]
[1, 3, 6]
I know I can iterate it and get the result but is it possible with list comprehension?
Seems like this would be more easily done in an iterative way:
size = 5
grid = [[1 for i in range(size)] for j in range(size)]
for i in range(1, size):
for j in range(1, size):
grid[i][j] = grid[i-1][j] + grid[i][j-1]
print grid
Result (spacing added by me manually):
[
[1, 1, 1, 1, 1],
[1, 2, 3, 4, 5],
[1, 3, 6, 10, 15],
[1, 4, 10, 20, 35],
[1, 5, 15, 35, 70]
]