Python和数据结构学习 --- 5

昨天懒了没写,今天也懒了.

这个是多维数组.在c/c++多维数组可以使用编译器帮你计算.但是在Python中没有这个功能.只好写类了.

代码如下:

class MulitArray:

    def __init__(self,*dimensions):

        assert len(dimensions) > 1

        self._dims = dimensions

        size = 1

        for d in dimensions:

            assert d > 0,"Dimeons must be >0"

            size*= d

        self._elements = Array(size)

        self._factors = Array(len(dimensions))

        self._computeFactors()

        

    def numDims(self):

        return len(self._dims)

    

    

    def length(self,dim):

        assert dim >= 1 and dim < len(self._dims),\

            "Dimension component out of range"

        #从1开始

        return self._dims[dim-1]

    

    def clear(self,value):

        self._elements.clear(value)

        

    def __getitem__(self,ndxTuple):

        assert len(ndxTuple) == self.numDims(),"Invalid # of array subscripts"

        index = self._computeIndex(ndxTuple)

        assert index is not None,"Array subscript out of range"

        return self._elements[index]

    

    def __setitem__(self,ndxTuple,value):

        assert len(ndxTuple) == self.numDims(),"Invalid # of array subscripts"

        index = self._computeIndex(ndxTuple)

        assert index is not None,"Array subscript out of range"

        self._elements[index] = value

        

    def _computeIndex(self,idx):

        offset  = 0

        for j in range(len(idx)):

            #其实这里也没必要设置的只要最后结果好就行

            if idx[j] < 0 or idx[j] >= self._dims[j]:

                return None

            else:

                offset += idx[j] * self._factors[j]

        return offset

    

    def _computeFactors(self):

        f = 1

        for i in range(self.numDims()-1,-1,-1):

            self._factors[i] = f

            f *= self._dims[i]

这个很简单,就是将多维数组映射到一维数组上,存取都使用了计算.

当然这里只是很简单的实现,往深入些的话 就得考虑很多了,有取取多维数组中的子数组,节约内存啥的

当然记得,<代码之美>上讲到关于映射的高级技巧的,还有c++中vararray和slice_array(不过好像很少有人用)也可以模拟出高维数组.

额,看书先..

你可能感兴趣的:(python)