I’m working on a basic program allows me to navigate in a two dimensions grid (for now 3X3), using a function specified with the initial point and all the steps moved on each axis, returning the end point. I want to raise an error if a specific point has been already visited, and I’m trying to do it by logging all previous points. This is my code:
JavaScript
x
11
11
1
matrix = [[1, 1], [1, 2], [1, 3], [2, 1], [2, 2], [2, 3], [3, 1], [3, 2], [3, 3]]
2
3
def position(inital_point,*steps):
4
end_point = inital_point
5
point_logs = []
6
point_logs += end_point
7
for step in steps:
8
end_point[0] += step[0]; end_point[1] += step[1]
9
point_logs += end_point
10
print(point_logs)
11
My problem is, I want to reference each point with a nested list inside the main list, but the code above is giving me this result:
JavaScript
1
3
1
position([1,1],[1,1],[1,1])
2
>>>[1, 1, 2, 2, 3, 3]
3
When I try to convert it to a nested list, I get:
JavaScript
1
14
14
1
matrix = [[1, 1], [1, 2], [1, 3], [2, 1], [2, 2], [2, 3], [3, 1], [3, 2], [3, 3]]
2
3
def position(inital_point,*steps):
4
end_point = inital_point
5
point_logs = []
6
point_logs += [end_point]
7
for step in steps:
8
end_point[0] += step[0]; end_point[1] += step[1]
9
point_logs += [end_point]
10
print(point_logs)
11
12
position([1,1],[1,1],[1,1])
13
>>> [[3, 3], [3, 3], [3, 3]]
14
Instead of simply [[1, 1],[2, 2],[3, 3]]
, please help!
Advertisement
Answer
This approach basically takes the last appended points from point_logs
and adds the new coordinates to it after which it is also appended.
JavaScript
1
9
1
def position(inital_point,*steps):
2
end_point = inital_point
3
point_logs = []
4
point_logs.append(end_point)
5
for step in steps:
6
x, y = point_logs[-1]
7
point_logs.append([x+step[0], y+step[1]])
8
print(point_logs)
9
Output
JavaScript
1
2
1
[[1, 1], [2, 2], [3, 3]]
2