def test_dequeuing_from_queue_removes_item(): queue = Queue() queue.enqueue(1) assert_equal(queue.empty(), False) assert_equal(queue.dequeue(), 1) assert_equal(queue.empty(), True)
def test_enqueuing_to_queue_adds_item_to_queue(): queue = Queue() assert_equal(queue.empty(), True) queue.enqueue(1) assert_equal(queue.empty(), False) assert_equal(queue.dequeue(), 1)
def flatorder(self, f): result = [] queue = Queue(self.__root) while not queue.empty(): cur_node = queue.exit() result.append(f(cur_node.value)) if cur_node.left is not None: queue.enter(cur_node.left) if cur_node.right is not None: queue.enter(cur_node.right) return result
def print_tree(self): """ 打印树的结构 :return: """ queue = Queue(self.__root) next_level = 1 now_node_count = 0 while not queue.empty(): cur_node = queue.exit() print str(cur_node) + "\t", now_node_count += 1 if now_node_count == next_level: print now_node_count = 0 next_level *= 2 if cur_node.left is not None: queue.enter(cur_node.left) if cur_node.right is not None: queue.enter(cur_node.right)
def lws(self, from_node, to_node): """ 在有向无环带权图里面查找最长路径 令list(s,t)是从s到t的最长带权路径。 那么可以使用递归式表示这个问题 list(s,t) = max(list(s,t-1))+list(t-1,t)(唯一) 用动态规划自下而上解决,因为自上而下解决首先遇到的问题就是 查找指向一个节点的节点在邻接表中比较困难 :param from_node: :param to_node: :return: """ __lws = {} # 为了计算方便,这里把开始节点到开始节点插入字典中, zero_edge = Edge(from_node, from_node) __lws[zero_edge] = 0 graph_stack = Queue() graph_stack.enter(from_node) while not graph_stack.empty(): cur_node = graph_stack.exit() cur_edge_list = self.__adj_list.get(cur_node) if cur_edge_list is None: print ",".join(map(lambda edge: str(edge), __lws.iteritems())) print ",".join(map(lambda edge: str(edge), __lws)) return __lws[Edge(from_node, to_node)] for edge_end_node in cur_edge_list: graph_stack.enter(edge_end_node.key) last_weighted_length = __lws[Edge(from_node, cur_node)] cur_edge = Edge(from_node, edge_end_node.key) cur_weight_length = last_weighted_length + edge_end_node.weight # 如果不存在这个边,那么就插入 if cur_edge not in __lws: __lws[cur_edge] = cur_weight_length # 如果存在,那么就把最大值插入 elif cur_weight_length > __lws[cur_edge]: __lws[cur_edge] = cur_weight_length print ",".join(map(lambda edge: str(edge), __lws.iteritems())) print ",".join(map(lambda edge: str(edge), __lws)) return __lws[Edge(from_node, to_node)]
def test_empty_returning_false_when_not_empty(): queue = Queue() queue.enqueue(1) assert_equal(queue.empty(), False)
def test_empty_returning_true_when_empty(): queue = Queue() assert_equal(queue.empty(), True)