Calculating cartesian coordinates using python

Question:

Having not worked with cartesian graphs since high school, I have actually found a need for them relevant to real life. It may be a strange need, but I have to allocate data to points on a cartesian graph, that will be accessible by calling cartesian coordinates. There needs to be infinite points on the graphs. For Eg.

                       ^
 [-2-2,a ][ -1-2,f ][0-2,k ][1-2,p][2-2,u]
 [-2-1,b ][ -1-1,g ][0-1,l ][1-1,q][1-2,v]
<[-2-0,c ][ -1-0,h ][0-0,m ][1-0,r][2-0,w]>
 [-2--1,d][-1--1,i ][0--1,n][1-1,s][2-1,x]
 [-2--2,e][-1--2,j ][0--2,o][1-2,t][2-2,y]
                       v

The actual values aren’t important. But, say I am on variable m, this would be 0-0 on the cartesian graph. I need to calculate the cartesian coordinates for if I moved up one space, which would leave me on l.

Theoretically, say I have a python variable which == (“0-1”), I believe I need to split it at the -, which would leave x=0, y=1. Then, I would need to perform (int(y)+1), then re-attach x to y with a ‘-‘ in between.

What I want to be able to do is call a function with the argument (x+1,y+0), and for the program to perform the above, and then return the cartesian coordinate it has calculated.

I don’t actually need to retrieve the value of the space, just the cartesian coordinate. I imagine I could utilise re.sub(), however I am not sure how to format this function correctly to split around the ‘-‘, and I’m also not sure how to perform the calculation correctly.

How would I do this?

Asked By: abkai

||

Answers:

To represent an infinite lattice, use a dictionary which maps tuples (x,y) to values.

grid[(0,0)] = m
grid[(0,1)] = l

print(grid[(0,0)])
Answered By: ninjagecko

I’m not sure I fully understand the problem but I would suggest using a list of lists to get the 2D structure.

Then to look up a particular value you could do coords[x-minX][y-minY] where x,y are the integer indices you want, and minX and minY are the minimum values (-2 in your example).

You might also want to look at NumPy which provides an n-dim object array type that is much more flexible, allowing you to ‘slice’ each axis or get subranges. The NumPy documentation might be helpful if you are new to working with arrays like this.

EDIT:
To split a string like 0-1 into the constituent integers you can use:

s = '0-1'
[int(x) for x in s.split('-')]
Answered By: robince

You want to create a bidirectional mapping between the variable names and the coordinates, then you can look up coordinates by variable name, apply your function to it, then find the next variable using the new set of coordinates produced by your function.

Mapping between numeric tuples you can apply your function to, and strings usable as keys in a dict, and back, is easy.

Answered By: grahaminn
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.