Example #1
0
def check_parens(text):
    parens = "()[]{}"    # 所有括号字符
    open_parens = "([{"  # 开括号字符
    opposite = {')':'(', ']':'[', '}':'{'}  # 表示配对关系的字典
    
    """括号生成器,每次调用返回text里的下一括号及其位置"""
    def parentheses(text):
        i, text_len = 0, len(text)
        while True:
            while i < text_len and text[i] not in parens:
                i += 1
            if i >= text_len:
                return
            yield text[i], i
            i += 1
            
    st = SStack()               # 保存括号的栈
    
    for pr, i in parentheses(text):   # 对text里各括号和位置迭代
        if pr in open_parens:        # 开括号,压进栈并继续
            st.push(pr)
        elif st.pop() != opposite[pr]:  # 匹配失败
            print("Unmatching is found at", i, "for", pr)
            return False
        # else:括号匹配成功,什么也不做,继续
        
    print("All parentheses are correctly matched.")
    return True
Example #2
0
def check_parens(text):
    parens = "()[]{}"
    open_parens = "([{"
    close_parens = ")]}"
    opposite = {')': '(', ']': '[', '}': '{'}

    # there are still some necessary function
    # ignore notation and strings
    def parentheses(text):
        i, text_len = 0, len(text)
        while True:
            while i < text_len and text[i] not in parens:
                i += 1
            if i >= text_len:
                return
            yield text[i], i
            i += 1

    st = SStack()
    for pr, i in parentheses(text):
        if pr in open_parens:
            st.push((pr, i))
        elif pr in close_parens:
            temp = st.pop()
            if temp[0] != opposite[pr]:
                print('Unmatching is found at', i, 'for', pr)
                print('The unmatching parentheses is found at', temp[1])
                return False
        # else: pass

    print('All parentheses are correctly matched.')
    return True
Example #3
0
def check_parens(text):
    parens = "()[]{}"
    open_parens = "([{"
    opposite = {")": "(", "}": "{", "]": "["}

    def parentheses(text):

        i, text_len = 0, len(text)
        while True:
            while i < text_len and text[i] not in parens:
                i += 1
            if i >= text_len:
                return
            yield text[i], i
            i += 1
    st = SStack()

    for pr, i in parentheses(text):
        if pr in open_parens:
            st.push(pr)
        elif st.pop() != opposite[pr]:
            print "Unmatching is found at", i , "for", pr
            return False
    print "All parentheses are correctly matched."
    return True
Example #4
0
 def process_entrace(self, key_list, filename):
     st = SStack()  #用栈存放每一轮的属性
     lq = LifoQueue(maxsize=0)  #用后进先出队列用于存放文件操作过程中的中间键值(用于新建新的对齐json)
     key_list.reverse()  #属性名列表反向,为了使最后按照正向的方式写入
     for i in key_list:
         st.push(i)  #将最开始外层的属性名压入栈中
     res = self.json_to_dataframe(st, lq)  #调用处理成dataframe的函数
     global node
     global relation
     path_node = 'static/yuanshi_csv/' + filename + '_node.csv'
     path_relation = 'static/yuanshi_csv/' + filename + '_relation.csv'
     node.to_csv(path_node, index=False)  #将df输出到csv文件,输出顺序为dataframe默认的列名顺序
     relation.to_csv(path_relation, index=False)
Example #5
0
def check_parens(text):
    """括号配对检查函数,text是被检查的正文串"""
    parens = "()[]{}"
    open_parens = "([{"
    opposite = {")": "(", "]": "[", "}": "{"}  # 表示配对关系的字典

    def parentheses(text):
        """括号生成器,每次调用返回text里的下一括号及其位置"""
        i, text_len = 0, len(text)
        while True:
            while i < text_len and text[i] not in parens:
                i += 1
            if i >= text_len:
                return
            yield text[i], i
            i += 1

    st = SStack()  # 保存括号的栈

    for pr, i in parentheses(text):
        if pr in open_parens:
            st.push(pr)
        elif st.pop() != opposite[pr]:
            print("Unmatching is found at", i, "for", pr)
            return False

    if not st.is_empty():
        while not st.is_empty():
            print("Unmatching for " + st.pop())

        return False

    print("All parentheses are correctly matched")
    return True
Example #6
0
def process_entrace(key_list, yuanshi_name_id):
    st = SStack()  #用栈存放每一轮的属性
    lq = LifoQueue(maxsize=0)  #用后进先出队列用于存放文件操作过程中的中间键值(用于新建新的对齐json)
    key_list.reverse()  #属性名列表反向,为了使最后按照正向的方式写入
    for i in key_list:
        st.push(i)  #将最开始外层的属性名压入栈中
    res = json_to_dataframe(st, lq, yuanshi_name_id)  #调用处理成dataframe的函数
    global property_node
    global relation
    global yuanshi_node
    property_node.to_csv('static/neo4j_csv/property_label.csv',
                         index=False)  #将df输出到csv文件,输出顺序为dataframe默认的列名顺序
    relation.to_csv('static/neo4j_csv/relation_label.csv', index=False)
    yuanshi_node.to_csv('static/neo4j_csv/yuanshi_label.csv', index=False)
Example #7
0
def process_entrace(key_list, baike_name, yuanshi_name):
    tree = lambda: collections.defaultdict(tree)
    global align_json  #全局变量,用于存储对齐和未对齐(做标记)的结果
    align_json = tree()
    st = SStack()  #用栈存放每一轮的属性
    lq = LifoQueue(maxsize=0)  #用后进先出队列用于存放文件操作过程中的中间键值(用于新建新的对齐json)
    key_list.reverse()  #属性名列表反向,为了使最后按照正向的方式写入
    for i in key_list:
        st.push(i)  #将最开始外层的属性名压入栈中
    res = other_align(st, lq, baike_name)  #调用对齐的控制函数
    align_json['院士名'] = yuanshi_name
    print("  ", json.dumps(align_json, ensure_ascii=False, indent=4))
    with open('./merge/fang_merge3.json', 'w') as f:
        f.write(json.dumps(align_json, ensure_ascii=False,
                           indent=4))  #设置不转换成ascii  json字符串首缩进
Example #8
0
def postorder_nonrec(t, proc):
    s = SStack()
    while t or not s.is_empty():
        while t:  # 下行循环,直到栈顶的两子树空
            s.push(t)
            t = t.left if t.left else t.right  # 能左就左,否则向右
        t = s.pop()  # 栈顶是应访问节点
        proc(t.data)
        if not s.is_empty() and s.top().left == t:
            t = s.top().right
        else:
            t = None
Example #9
0
def postorder_nonrec(t, proc):
    s = SStack()
    while t is not None or not s.is_empty():
        while t is not None:
            s.push(t)
            t = t.left if t.left else t.right
        t = s.pop()
        proc(t.data)
        if not s.is_empty() and s.top().left == t:
            t = s.top().right
        else:
            t = None
Example #10
0
 def entries(self):
     t, s = self._root, SStack()
     while t is not None or not s.is_empty():
         s.push(t)
         t = t.left
     t = s.pop()
     yield t.data.key, t.data.value
     t = t.right
def DFS_graph(graph, v0):
    vnum = graph.vertex_num()
    visited = [0] * vnum  # visited记录已访问顶点
    visited[v0] = 1
    DFS_seq = [v0]  # 记录遍历序列
    st = SStack()
    st.push((0, graph.out_edges(v0)))
    while not st.is_empty():
        i, edges = st.pop()
        if i < len(edges):
            v, e = edges[i]
            st.push((i + 1, edges))
            if not visited[v]:
                DFS_seq.append(v)
                visited[v] = 1
                st.push((0, graph.out_edges(v)))
    return DFS_seq
Example #12
0
 def preorder_elements(self):
     t, s = self._root, SStack()
     while t is not None or not s.is_empty():
         while t is not None:
             s.push(t.right)
             yield t.data
             t = t.left
         t = s.pop()
def DFS_seq(graph, v0):
    vnum = graph.vertex_num()
    visited = [0]*vnum
    visited[v0] = 1
    dfs_seq = [v0]
    st = SStack()
    st.push((0, graph.out_edges(v0)))
    while not st.is_empty():
        i, edges = st.pop()
        if i < len(edges):
            v, e = edges[i]
            st.push((i + 1, edges))
            if visited[v] == 0: # unvisited node
                dfs_seq.append(v)
                visited[v] = 1
                st.push((0, graph.out_edges(v)))
    return dfs_seq
Example #14
0
def DFS_seq(graph, v0):
    vnum = graph.vertex_num()
    visited = [0]*vnum # 生成访问记录,以供检测。
    visited[v0] = 1 # visited记录已访问顶点
    dfs_seq = [v0] # Dfs_seq记录遍历序列
    st = SStack()
    st.push((0, graph.out_edges(v0))) # 入栈(i, edges),说明下次应访问边edges[i],即压入了某个顶点的所有出边信息
    while not st.is_empty(): # 循环一遍后再看:运用和“先进后出,后进先出”的特点,我们访问完v0后会先去访问v顶点,而不是i+1顶点
        i, edges = st.pop() # 将栈中的顶点的初始计算点和出边信息取出。
        if i < len(edges): # 查看是否有边,以及有几个边
            v, e = edges[i] # 获取出边点的信息以及边的权重
            st.push((i + 1, edges)) # 下次再访问这个点的时候将访问edges[i+1],即访问下一个边
            if visited[v] == 0: # 检测出边点v是否被访问过,若未被访问,访问其记录可达顶点。
                dfs_seq.append(v) # 将被访问的v添加进序列。
                visited[v] = 1# 记录v已经被访问
                st.push((0, graph.out_edges(v))) # 压入v,访问v的出边点
        # 一直循环,直到所有点被访问。
    return dfs_seq
Example #15
0
 def values(self):
     t, s = self._root, SStack()
     while t or not s.is_empty():
         while t:
             s.push(t)
             t = t.left
         t = t.pop()
         yield t.data.value
         t = t.right
Example #16
0
def postorder_s(t, proc):
    s = SStack()
    while t is not None or not s.is_empty():
        while t is not None:
            s.push((t, t.right))
            t = t.left
        (m, n) = s.pop()
        if n:
            s.push((m, None))
            t = n
        else:
            proc(m.data)
Example #17
0
def maze_solver(maze, start, end):
    if start == end:
        print(start)
        return
    st = SStack()
    mark(maze, start)
    st.push((start, 0))              # 入口和方向0的序对入栈
    while not st.is_empty():
        pos, nxt = st.pop()          # 取栈顶及其探查方向
        for i in range(nxt, 4):     # 依次检查未探查方向
            nextp = (pos[0] + dirs[i][0], pos[1] + dirs[i][1])
            if nextp == end:         # 到达出口,打印路径
                print_path(end, pos, st)
                return
            if passable(maze, nextp):
                st.push((pos, i+1))   # 原位置和下一方向入栈
                mark(maze, nextp)
                st.push((nextp, 0))   # 新位置入栈
                break  # 退出内层循环,下次迭代将以新栈顶为当前位置继续
    print("No path found")
def maze_solver_stack(maze, start, end):
    """"迷宫的栈解法"""
    if start == end:
        print(start)
        return
    st = SStack()
    mark(maze, start)
    st.push((start, 0))
    while not st.is_empty():
        pos, nxt = st.pop()
        for i in range(nxt, 4):
            nextp = (pos[0] + dirs[i][0], pos[1] + dirs[i][1])
            if nextp == end:
                #print_path(end, pos, st) 将nextp和pos两个位置和栈中的位置一起输出
                return True
            if passable(maze, nextp):
                st.push((pos, i + 1))
                mark(maze, nextp)
                st.push((nextp, 0))
                break
    print("No path found.")
Example #19
0
def preorder_nonrec(t, proc):
    s = SStack()
    while t is not None or not s.is_empty():
        while t:
            proc(t.data)
            s.push(t.right)  # 右分支入栈
            t = t.left
        t = s.pop()  # 遇到空树,回溯
Example #20
0
def preorder_s(t, proc):
    s = SStack()
    while t is not None or not s.is_empty():
        while t is not None:
            proc(t.data)
            s.push(t.right)
            t = t.left
        t = s.pop()
Example #21
0
def preorder_elements(t):
    s = SStack()
    while t is not None or not s.is_empty():
        while t:
            s.push(t.right)  # 右分支入栈
            yield t.data
            t = t.left
        t = s.pop()  # 遇到空树,回溯
Example #22
0
def preorder_elems(t):
    s = SStack()
    while t is not None or not s.is_empty():
        while t is not None:
            s.push(t.right)
            yield t.data
            t = t.left
        t = s.pop()
Example #23
0
def norec_fact(n):
    res = 1
    st = SStack()
    while n > 0:
        st.push(n)
        n -= 1
    while not st.is_empty():
        res *= st.pop()
    return res
Example #24
0
def process_entrace(key_list, yuanshi_name_id):
    st = SStack()  #用栈存放每一轮的属性
    lq = LifoQueue(maxsize=0)  #用后进先出队列用于存放文件操作过程中的中间键值(用于新建新的对齐json)
    key_list.reverse()  #属性名列表反向,为了使最后按照正向的方式写入
    for i in key_list:
        st.push(i)  #将最开始外层的属性名压入栈中
    res = json_to_dataframe(st, lq, yuanshi_name_id)  #调用处理成dataframe的函数
    global property_node
    global relation
    global yuanshi_node
    property_node.to_csv('static/neo4j_csv/property_label.csv',
                         index=False)  #将df输出到csv文件,输出顺序为dataframe默认的列名顺序
    relation.to_csv('static/neo4j_csv/relation_label.csv', index=False)
    yuanshi_node.to_csv('static/neo4j_csv/yuanshi_label.csv', index=False)
    # 表示先删除当前已有的节点和关系
    cypher_delete = '''MATCH(b) detach delete b
                  '''
    test_graph.run(cypher_delete)
    # 表示加载属性到neo4j
    cypher_node = '''LOAD CSV WITH HEADERS FROM "http://localhost:5000/static/neo4j_csv/property_label.csv" AS line
                     MERGE (p:attribute{id:line.property_id,name:line.name})
                  '''
    test_graph.run(cypher_node)

    # 表示加载实体到neo4j
    cypher_node = '''LOAD CSV WITH HEADERS FROM "http://localhost:5000/static/neo4j_csv/yuanshi_label.csv" AS line
                     MERGE (p:yuanshi{id:line.yuanshi_id,name:line.name})
                  '''
    test_graph.run(cypher_node)

    # 表示加载关系到neo4j
    cypher_relation = '''LOAD CSV WITH HEADERS FROM "http://localhost:5000/static/neo4j_csv/relation_label.csv" AS line  
                         match (from:yuanshi{id:line.from_id}),(to:attribute{id:line.to_id})  
                         merge (from)-[r:rel{pro1:line.pro1}]->(to)
                      '''
    test_graph.run(cypher_relation)
def trans_infix_suffix(line):
    st = SStack()
    exp = []

    for x in tokens(line):
        if x not in infix_operators:  # 运算对象直接送出
            exp.append(x)
        elif st.is_empty() or x == '(':  # 左括号进栈
            st.push(x)
        elif x == ')':  # 处理右括号
            while not st.is_empty() and st.top() != '(':
                exp.append(st.pop())
            if st.is_empty():  # 没找到左括号
                raise SyntaxError("Missing '('.")
            st.pop()  # 弹出左括号
        else:  # 处理算术运算符,运算符都看作左结合
            while(not st.is_empty() and
                  priority[st.top()] >= priority[x]):
                exp.append(st.pop())
            st.push(x)

    while not st.is_empty():  # 送出栈里面剩下的运算符
        if st.top() == '(':   # 多余的左括号
            raise SyntaxError("Extra '('.")
        exp.append(st.pop())

    return exp
def Ack_l(m, n):
    st = SStack()
    st.push(m)
    while not st.is_empty():
        m = st.pop()
        if m == 0:
            n += 1
        elif n == 0:
            st.push(m - 1)
            n = 1
        elif n != 0:
            st.push(m - 1)
            st.push(m)
            n -= 1
    return n
def Inf2Suf(line):
    st = SStack()
    exp = []

    for x in tokens(line): 
        if x not in infix_operators:
            exp.append(x)
        elif st.is_empty() or x == '(':
            st.push(x)
        elif x == ')':
            while not st.is_empty() and st.top() != '(':
                exp.append(st.pop())
            if st.is_empty():
                raise SyntaxError("Missing '('.")
            st.pop()
        else: 
            while (not st.is_empty() and
                     priority[st.top()] >= priority[x]):
                exp.append(st.pop())
            st.push(x)

    while not st.is_empty():
        if st.top() == '(':
            raise SyntaxError("Extra '('.")
        exp.append(st.pop())

    return exp
 def __init__(self, text_):
     self._list = SStack()
     self.__text = text_
class IsLackBracket:
    def __init__(self, text_):
        self._list = SStack()
        self.__text = text_

    def is_lack_bracket(self):
        i = 0
        while True:
            while i < len(self.__text):
                if self.__text[i] not in ("([{)]}"):
                    i += 1
                    break
                if self.__text[i] in ("([{"):
                    self._list.push(self.__text[i])
                    i += 1
                    break
                if self.__text[i] is ")" and self._list.top() is "(":
                    self._list.pop()
                elif self.__text[i] is "]" and self._list.top() is "[":
                    self._list.pop()
                elif self.__text[i] is "}" and self._list.top() is "{":
                    self._list.pop()
                elif self.__text[i] in (")]}"):
                    raise SStackError("%s不匹配" % self.__text[i])
                i += 1
            else:
                if self._list.is_empty():
                    raise SStackError("%s不匹配" % self._list.top())
                else:
                    print("匹配")
def maze_solver_stack(maze, start, end):  # depth first search
    if start == end:
        print(start)
        return
    st = SStack()
    mark(maze, start)
    st.push((start, 0))
    while not st.is_empty():
        pos, nxt = st.pop()
        for i in range(nxt, 4):
            nextp = (pos[0] + dirs[i][0], pos[1] + dirs[i][1])
            if nextp == end:
                print(end, end=' ')
                print(pos, end=' ')
                # print('Succeed!')
                while not st.is_empty():
                    print(st.pop()[0], end=' ')
                print('')
                return
            if passable(maze, nextp):
                st.push((pos, i + 1))
                mark(maze, nextp)
                st.push((nextp, 0))
                break
    print('No path found.')