zoukankan      html  css  js  c++  java
  • 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!='	'):
                    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()
    

      

  • 相关阅读:
    国内乡村安防全面建设仍需推进,EasyNVR/EasyGBS/EasyCVR平台助力治安防控
    TSINGSEE青犀视频播放视频流的编码格式和封装格式有什么关系?
    全景摄像头怎么接入网页进行视频直播?
    EasyNTS编译报错could not read Username for XXXXX
    【LOJ#3005】Limited Memory
    【BZOJ2407】探险
    【洛谷P4480】餐巾计划问题
    【CF163E】e-Government
    【洛谷P4332】三叉神经树
    【洛谷P7518】宝石
  • 原文地址:https://www.cnblogs.com/zhj11226/p/6286843.html
Copyright © 2011-2022 走看看