Python和数据结构学习 --- 0
好早前就想开始写了,可以一直懒没写.
书参考的是<Data Structures and Algorithms Using Python>基本是照着来.估计也会把里面的题目做做.
看完后打算看稍微难些的<Python Algorithms - Mastering Basic Algorithms in the Python Language>.
基本是自己的学习笔记.记录下而已.
扯了这么多蛋.开始.
首先第一个基本的结构是一维Array(后面还有多维的).它是个静态数组.可以迭代,获取设置值.
实现如下:
import ctypes class Array: def __init__(self,size): assert size > 0,"Array size must be >0" self._size = size PyArrayType = ctypes.py_object * size self._elements = PyArrayType() self.clear(None) def __len__(self): return self._size def clear(self,value): for i in range(len(self)): self._elements[i] = value def __getitem__(self,index): assert index >= 0 and index < len(self),"Array subsctipt out of range" return self._elements[index] def __setitem__(self,index,value): assert index >= 0 and index < len(self),"Array subsctipt out of range" self._elements[index] = value def __iter__(self): return _ArrayIterator(self._elements) class _ArrayIterator: def __init__(self,theArray): self._arrayRef = theArray self._curNdx = 0 def __iter__(self): return self #注意这里提供的是next 而书中提供的是__next__它是对应这3版本中的 def next(self): if self._curNdx < len(self._arrayRef): entry = self._arrayRef[self._curNdx] self._curNdx += 1 return entry else: raise StopIteration
测试也很简单.
发现IPython超好,测试修改啥的都可以在一起.
当然了像Array这个数据结构可以直接使用list实现有2中方法,一是直接继承UserList,或者讲list作为内部元素.这里使用的第二中.
class Array: def __init__(self,size): self._size = size self._elements = [None]*size def __len__(self): return self._size def clear(self,value): for i in range(len(self)): self._elements[i] = value def __getitem__(self,index): return self._elements[index] def __setitem__(self,index,value): self._elements[index] = value def __iter__(self): return iter(self._elements)
好好了.明天搞二维的,睡觉先..