def _post_order(self, node): """ Utility method for computing post-order of a binary tree using iterative algorithm. """ visit = [] tree, size = self.tree.tree, self.tree.size s = Stack() s.push(node) last = OneDimensionalArray(int, size) last.fill(False) while not s.is_empty: node = s.peek l, r = tree[node].left, tree[node].right cl, cr = l is None or last[l], r is None or last[r] if cl and cr: s.pop() visit.append(tree[node]) last[node] = True continue if not cr: s.push(r) if not cl: s.push(l) return visit
def __new__(cls, *vertices): obj = object.__new__(cls) num_vertices = len(vertices) obj.vertices = [vertex.name for vertex in vertices] for vertex in vertices: obj.__setattr__(str(vertex.name), vertex) obj.matrix = OneDimensionalArray(OneDimensionalArray, num_vertices) for i in range(num_vertices): obj.matrix[i] = OneDimensionalArray(bool, num_vertices) obj.matrix[i].fill(False) obj.edge_weights = dict() return obj
def __new__(cls, *vertices): obj = object.__new__(cls) num_vertices = len(vertices) obj.vertices = OneDimensionalArray(AdjacencyMatrixGraphNode, num_vertices) for vertex in vertices: obj.vertices[vertex.name] = vertex obj.matrix = OneDimensionalArray(OneDimensionalArray, num_vertices) for i in range(num_vertices): obj.matrix[i] = OneDimensionalArray(bool, num_vertices) obj.matrix[i].fill(False) return obj
def __new__(cls, array): obj = object.__new__(cls) obj.array = OneDimensionalArray(type(array[0]), array) obj.tree = [0] * (obj.array._size + 2) obj.flag = [0] * (obj.array._size) for index in range(obj.array._size): obj.update(index, array[index]) return obj
def __new__(cls, maxsize=None, top=0, items=None, dtype=int): if not _check_type(maxsize, int): raise ValueError("maxsize is missing.") if not _check_type(top, int): raise TypeError("top is not of type int.") if items == None: items = OneDimensionalArray(dtype, maxsize) if not _check_type(items, OneDimensionalArray): raise ValueError("items is not of type, OneDimensionalArray") if items._size > maxsize: raise ValueError("Overflow, size of items %s is greater " "than maxsize, %s" % (items._size, maxsize)) obj = object.__new__(cls) obj.maxsize, obj.top, obj.items, obj.dtype = \ maxsize, top, items, items._dtype return obj
def test_Stack(): s = Stack(maxsize=3, top=0) s.push(1) s.push(2) s.push(3) assert s.top == 3 assert str(s) == '[1, 2, 3]' raises(ValueError, lambda: s.push(4)) assert s.pop() == 3 assert s.pop() == 2 assert s.pop() == 1 assert s.top == 0 raises(ValueError, lambda: s.pop()) raises(ValueError, lambda: Stack()) raises(TypeError, lambda: Stack(maxsize=8, top=3.5)) raises(ValueError, lambda: Stack(maxsize=5, top=0, items=[1, 2, 3])) raises(ValueError, lambda: Stack(maxsize=5, top=0, items=OneDimensionalArray(int, 6))) raises(NotImplementedError, lambda: Stack(implementation='', maxsize=5, top=0))