Python和数据结构学习 --- 3
下面是使用Array实现Vector.也就是Python中自带的list().
代码如下:
class Vector: def __init__(self): self._length = 0 self._capacity = 2 self._array = Array(self._capacity) def __len__(self): return self._length def __contains__(self,item): for v in self: if v == item: return True return False def __getitem__(self,index): return self._array[index] def __setitem__(self,index,value): self._array[index] = value def __new_array(self): oldCap = self._capacity newCap = self._capacity * 2 newArray = Array(newCap) for i,v in enumerate(self._array): newArray[i] = v self._array = newArray self._capacity = newCap def append(self,item): if self._length == self._capacity: self.__new_array() self._array[self._length] = item self._length += 1 def insert(self,ndx,item): if self._length == self._capacity: self.__new_array() for i in range(self._length,ndx,-1): self[i] = self[i-1] self._array[ndx] = item self._length += 1 def remove(self,ndx): for i in range(ndx,self._length): self[i] = self[i+1] self._length -= 1 def indexOf(self,item): for i,v in enumerate(self): if v == item: return i return -1 def extend(self,otherVector): for v in otherVector: self.append(v) def subVector(self,f,t): newV = Vector() for i in range(f,t): newV.append(self._array[i]) return newV def __iter__(self): return _VectorIterator(self) class _VectorIterator: def __init__(self,theVector): self._vectorRef = theVector self._curNdx = 0 def __iter__(self): return self def next(self): if self._curNdx < len(self._vectorRef): entry = self._vectorRef[self._curNdx] self._curNdx += 1 return entry else: raise StopIteration
测试基本是跟list一样.
中间涉及到一个小东东.想要在Python隐藏函数,数据.只需要在前面加上`__`就可以了.当然数据,函数还在.只是换了一个名字而已.具体可以看<Python高级编程>(记得..).
睡觉先...