Reputation: 171
I have a dictionary of coordinate pairs and integers that go with those pairs. The first problem is that some of the points are negative.
{(0, 0): 1, (-1, -1): 2, (1, -1): 3, (1, 1): 4}
to
+---+---+---+
| 0 | 0 | 4 |
+---+---+---+
| 0 | 1 | 0 |
+---+---+---+
| 2 | 0 | 3 |
+---+---+---+
I believe I have to adjust all the pairs so they are greater than zero so I can use them as row, column pairs for a matrix. Then the insertion is the next. I believe that python only has nested lists not matrices so I would want a numpy array.
Upvotes: 3
Views: 433
Reputation: 1798
import numpy as np
def make_array(data):
# In your example row is the second index and col is the first.
# Also positive row indexes go in up direction.
c, r = np.array(zip(*data.keys()))
rows = r.max()-r.min()+1
cols = c.max()-c.min()+1
result = np.zeros((rows, cols), dtype=int)
for k, v in data.iteritems():
# Minus before first index required for
# the last row contain 2, 0, 3 in the example.
# Also numpy successfully handle negative indexes
# and inversion not required
result[-k[1]+1, k[0]+1] = v
return result
Your test case:
data = {(0, 0): 1, (-1, -1): 2, (1, -1): 3, (1, 1): 4}
print make_array(data)
Result:
[[0 0 4]
[0 1 0]
[2 0 3]]
Example with different rows and columns count:
data = {(0, 0): 1, (-1, -1): 2, (1, -1): 3, (1, 1): 4, (2, 1): 5}
print make_array(data)
Result:
----------- "-First" column
| ----- Second column
| |
[[0 0 4 5] <-- First row
[0 1 0 0] <-- Zero row
[2 0 3 0]] <-- "-First" row
Upvotes: 1
Reputation: 251106
Using pure Python:
def solve(d):
x_min, y_min = map(min, zip(*d))
x_max, y_max = map(max, zip(*d))
arr = [[0]*(x_max-x_min+1) for _ in xrange(y_max-y_min+1)]
for i, y in enumerate(xrange(y_min, y_max+1)):
for j, x in enumerate(xrange(x_min, x_max+1)):
arr[i][j] = d.get((x, y), 0)
return arr[::-1]
Output:
solve({(0, 0): 1, (-1, -1): 2, (1, -1): 3, (1, 1): 4})
Out[80]:
[[0, 0, 4],
[0, 1, 0],
[2, 0, 3]]
solve({(0, 0): 1, (-1, -1): 2, (1, -1): 3, (1, 1): 4, (2, 2):30, (-3, -4):100})
Out[82]:
[[0, 0, 0, 0, 0, 30],
[0, 0, 0, 0, 4, 0],
[0, 0, 0, 1, 0, 0],
[0, 0, 2, 0, 3, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[100, 0, 0, 0, 0, 0]]
Upvotes: 1
Reputation: 42778
import numpy
s = {(0, 0): 1, (-1, -1): 2, (1, -1): 3, (1, 1): 4}
x = numpy.array([k+(v,) for k,v in s.iteritems()])
x[:,0]-=x[:,0].min()
x[:,1]-=x[:,1].min()
w = numpy.zeros((x[:,0].max()+1,x[:,1].max()+1))
w[x[:,:2].T.tolist()]=x[:,2]
the resut:
>>> w
array([[ 2., 0., 0.],
[ 0., 1., 0.],
[ 3., 0., 4.]])
Upvotes: 0