Пример #1
0
    def __init__(self, regex):
        """
		Initializes the NFA from the specified regular expression.

		:param regex: the regular expression
		"""
        self.regex = regex
        m = len(regex)
        self.m = m
        ops = Stack()
        graph = Digraph(m + 1)
        for i in range(0, m):
            lp = i
            if (regex[i] == '(' or regex[i] == '|'):
                ops.push(i)
            elif (regex[i] == ')'):
                or_ = ops.pop()

                # 2-way or operator
                if (regex[or_] == '|'):
                    lp = ops.pop()
                    graph.add_edge(lp, or_ + 1)
                    graph.add_edge(or_, i)
                elif (regex[or_] == '('):
                    lp = or_
                else:
                    assert False
            if (i < m - 1 and regex[i + 1] == '*'):
                graph.add_edge(lp, i + 1)
                graph.add_edge(i + 1, lp)
            if (regex[i] == '(' or regex[i] == '*' or regex[i] == ')'):
                graph.add_edge(i, i + 1)
        if (ops.size() != 0):
            raise ValueError("Invalid regular expression")
        self.graph = graph
Пример #2
0
def evaluate():
    ops = Stack()
    vals = Stack()

    while not stdio.isEmpty():
        # Read token, push if operator
        s = stdio.readString()
        if s == "(": pass
        elif s == "+": ops.push(s)
        elif s == "-": ops.push(s)
        elif s == "*": ops.push(s)
        elif s == "/": ops.push(s)
        elif s == "sqrt": ops.push(s)
        elif s == ")":
            # Pop, evaluate and push result if token is ")"
            op = ops.pop()
            v = vals.pop()
            if op == "+": v = vals.pop() + v
            elif op == "-": v = vals.pop() - v
            elif op == "*": v = vals.pop() * v
            elif op == "/": v = vals.pop() / v
            elif op == "sqrt": v = math.sqrt(v)
            vals.push(v)
        else:
            vals.push(float(s))
    stdio.writeln(vals.pop())