Welcome, guest | Sign In | My Account | Store | Cart

From a multidimensional array to a flat array avoiding numpy. The code could be better?

Python, 44 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class ndim:             # from nD array to flat array
    def __init__(self,arr_dim):
        self.dimensions=arr_dim
        print "***dimensions***"
        print self.dimensions
        self.numdimensions=len(arr_dim) 
        print "***numdimension***"
        print self.numdimensions
        self.gridsize=reduce(lambda x, y: x*y, arr_dim)
        print self.gridsize
    def getcellindex(self, location):
        cindex = 0
        cdrop = self.gridsize
        for index in xrange(self.numdimensions):
            cdrop /= self.dimensions[index]
            cindex += cdrop * location[index]
        return cindex
    def getlocation(self, cellindex):
        res = []
        for size in reversed(self.dimensions):
            res.append(cellindex % size)
            cellindex /= size
        return res[::-1]

# how to use ndim class
arr_dim = [3,3,2,2]
n=ndim(arr_dim)
print "*****n.getcellindex((0,0,0,0))"
print n.getcellindex((0,0,0,0))
print "*****n.getcellindex((0,0,1,1))"
print n.getcellindex((0,0,1,1))
print "*****n.getcellindex((0,1,0,0))"
print n.getcellindex((0,1,0,0))
print "*****n.getcellindex((2,2,1,1))"
print n.getcellindex((2,2,1,1))
print
print "*****n.getlocation(0) "
print n.getlocation(0)
print "*****n.getlocation(3) "
print n.getlocation(3)
print "*****n.getlocation(4) "
print n.getlocation(4)
print "*****n.getlocation(35) "
print n.getlocation(35)
Created by Roberto Bello on Fri, 21 Mar 2014 (MIT)
Python recipes (4591)
Roberto Bello's recipes (3)

Required Modules

  • (none specified)

Other Information and Tasks