空老吹的一亩三分地

三十未立啊……

 

python 一遍式四则运算

#!/usr/bin/python
#coding: utf-8

INTEGER = 'INTEGER'
PLUS    = '+'
MINUS   = '-'
MUL     = '*'
DIV     = '/'
LC      = '('
RC      = ')'
EOF     = 'EOF'

class Token(object):
    def __init__(self, typ, val):
        self.typ = typ;
        self.val = val;

    def __str__(self):
        return "Token('{typ}','{val}')".format(typ=self.typ, val=self.val)

    def __repr__(self):
        return self.__str__()

class Lexer(object):
    def __init__(self, text):
        self.text = text
        self.pos = 0
        self.cur_token = None;
        self.status = 0

    def next_token(self):
        if self.pos > len(self.text) -1:
            return Token(EOF, '')

        ch = ''
        while True:
            ch = self.text[self.pos]
            self.pos+=1

            if (ch!=' ' and ch!='\t'):
                break;

        if self.status==0:
            if ch.isdigit():
                self.status = 1
                return Token(INTEGER, int(ch + self.next_token().val))
            else:
                return Token(ch, ch)
        elif self.status==1:
            if ch.isdigit():
                return Token(INTEGER, ch + self.next_token().val)
            else:
                self.pos -= 1
                self.status = 0
                return Token(INTEGER, '')
            
class Interpreter(object):
    def __init__(self, lexer):
        self.lexer = lexer
        self.cur_token = lexer.next_token()

    def error(self):
        raise Exception("syntax error") 

    def eat(self, typ):
        tok = self.cur_token
        if (tok.typ == typ):
            self.cur_token = self.lexer.next_token()
            return tok.val
        else:
            self.error()

    def factor(self):
        if (self.cur_token.typ == INTEGER):
            tok = self.cur_token
            self.eat(INTEGER)
            return tok.val
        elif self.cur_token.typ == LC:
            self.eat(LC)
            result = self.expr()
            self.eat(RC)
            return result
        else:
            self.error()

    def term(self):
        result = self.factor()
        
        while self.cur_token.typ in (MUL, DIV):
            if (self.cur_token.typ==MUL):
                self.eat(MUL)
                result = result * self.factor()
            elif (self.cur_token.typ==DIV):
                self.eat(DIV)
                result = result / self.factor()

        return result

    def expr(self):
        result = self.term()
        
        while self.cur_token.typ in (PLUS, MINUS):
            if (self.cur_token.typ==PLUS):
                self.eat(PLUS)
                result = result + self.term()
            elif (self.cur_token.typ==MINUS):
                self.eat(MINUS)
                result = result - self.term()

        return result


def main():
    print("expr2")
    while True:
        text = raw_input("calc> ")
        if not text:
            continue

        if text=="exit":
            break;

        lex = Lexer(text)
        calc = Interpreter(lex)
        result = calc.expr()
        print(result)

if __name__ == "__main__":
    main()

  

posted on 2017-01-15 11:49  空老吹  阅读(199)  评论(0编辑  收藏  举报

导航