Reputation: 49
I'm trying to do a project where I need to track a robots final position [0, 0] after giving it limitless coordinates. The coordinates can also be in negative. For example north equals -10 is the same as south equals 10. So the coordinates are in the order of north, east, south, and west.
Example arguments: track_robot(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
, track_robot(20, 30, 10, 40)
, track_robot(10, -10, -10, 10)
This is my code:
# give as much coordinates as you want to the bot and return it's final position.
# north, east, south, west
def track_robot(*steps):
pos = []
north = 0
east = 0
south = 0
west = 0
for coord in steps:
if steps.index(coord) % 2 == 0:
if steps.index(coord) % 4 == 0:
if coord < 0:
south += coord
else:
north += coord
else:
if coord < 0:
north += abs(coord)
else:
south -= coord
else:
I managed to handle the y axis so north and south using their index values in the *steps
variable, but couldn't seem to come up with an idea how to do it for the x axis(east and west). I got stuck at the end of my code. Can you please help me?
Upvotes: 0
Views: 326
Reputation: 1683
Instead of using a for looping and indexing, you can work with a list as a input and extract the 4 coordinates as 4 different arrays. The trick is the reshape function for numpy library.
import numpy as np
def track_robot(*steps):
"""
Input: 'steps' is a list of numbers: coordinates N,E,S,W
Returns 4 different arrays for N, E, S and W
"""
# Convert list to array (numpy array)
arr = np.asarray(steps)
# Check array has same steps for the same coords (N,E,S,W)
if len(arr) % 4 != 0:
# Calculate how much coords left:
# If length % 4 != 0, then length/4 has a decimal part.
# If we get the integer part of the fraction we can know the
# next subgroup of coordinates we need. We multiply by 4
# and subtract the length so we calculated how many coord
# we don't have (E, S and/or W).
nzeros = 4*(int(len(arr)/4)+1)-len(arr)
# Add the number of zeros (no-movement in previous coords)
arr = np.pad(arr, (0, nzeros), 'constant')
# Now, we reshape as a matrix 4xM, where M columns = len(arr)/4
# and 4 rows, each one for each coordinate.
arr = arr.reshape([int(len(arr)/4),4], order = 'F')
# Now split columns
north = arr[0]
east = arr[1]
south = arr[2]
west = arr[3]
return north,east,south,west
First, you have to convert the list to a numpy array. I assumed coordinates are always sorted the same: North, East, South, West, so we can reshape the array as a matrix of 4 rows and extract each row individually. But for using reshape function, the length of the array has to be % 4 == 0. Therefore, if it isn't, we have to fill it with zeros using the pad function. (zero = no-movement for that coordinate).
Try with:
# 1 = North, 2 = East, 3 = South, 4 = West. Last steps for
# south and west are missing.
track_robot(1,2,3,4,1,2,3,4,1,2,3,4,1,2)
If it was helpful consider to vote as the solution :)
Upvotes: 1