Monday, October 26, 2015

Implementing recursive descent parser for sample language

PROGRAM

filename: b7.py

"""
exp ::= term | exp + term | exp - term
term ::= factor | factor * term | factor / term
factor ::= number | ( exp )
"""
class Calculator():
    def __init__(self, tokens):
        self._tokens = tokens
        self._current = tokens[0]
    def exp(self):
        result = self.term()
        while self._current in ('+', '-'):
            if self._current == '+':
                self.next()
                result += self.term()
            if self._current == '-':
                self.next()
                result -= self.term()
        return result
    def factor(self):
        result = None
        if self._current[0].isdigit() or self._current[-1].isdigit():
            result = float(self._current)
            self.next()
        elif self._current is '(':
            self.next()
            result = self.exp()
            self.next()
        return result
    def next(self):
        self._tokens = self._tokens[1:]
        self._current = self._tokens[0] if len(self._tokens) > 0 else None
    def term(self):
        result = self.factor()
        while self._current in ('*', '/'):
            if self._current == '*':
                self.next()
                result *= self.term()
            if self._current == '/':
                self.next()
                result /= self.term()
        return result

if __name__ == '__main__':
    flag=0
    while True:
        lst = list(raw_input('> ').replace(' ', ''))
        tokens = []
        for i in range(len(lst)):
            if(i==len(lst)-1 and lst[i] in ('*','/','-','+')):
                print "Syntax Error String not accepted"
                flag=1
                break
            if lst[i].isdigit() and i > 0 and (tokens[-1].isdigit() or tokens[-1][-1] is '.'):
                tokens[-1] += lst[i]
            elif lst[i] is '.' and i > 0 and tokens[-1].isdigit():
                tokens[-1] += lst[i]
            else:
                tokens.append(lst[i])
            
        if flag!=1:       
            print Calculator(tokens).exp() 

OUTPUT

Amols-MacBook-Air:Codes Darwin$ python b7.py
> 5+8*9 
77.0
> 4/4
1.0
> 4+2+
Syntax Error String not accepted
> ^CTraceback (most recent call last):
  File "b7.py", line 47, in <module>
    lst = list(raw_input('> ').replace(' ', ''))
KeyboardInterrupt

No comments:

Post a Comment

Perform a suitable assignment using Xen Hypervisor or equivalent open source to configure it. Give necessary GUI.

 To install kvm on Fedora:  yum install kvm  yum install virt-manager libvirt libvirt-python python-virtinst  su -c "yum install @v...