A programming language compiler check your programs for synt

A programming language compiler check your programs for syntax errors, but frequently a lack of one symbol (such as missing comment ender */or)) will cause the compiler to spill out hundred lines of diagnostic without identifying real error. A useful tool is a program that checks whether symbols are balanced. In other words, every {must correspond to a}, every [to a], and so on. For the program to be useful, we must not only report the mismatches but also attempt to identify where the mismatches occur -identify the line number where the tokens are seen. We will report the first error. Comments line will be only start with//(do not consider/* */) symbols: ([{and matching ones Algorithm: Make an empty stack. Read tokens until the end of file. If the token is is an opening symbol, push it onto the stack. If it is an closing symbol and if the stack is empty, report an error. Otherwise, pop the stack. If the symbol popped is not the corresponding opening symbol, then report an error. At the end of the file, if the stack is not empty, then report an error. Program input: Program experts input from input file: Robotinput.txt Program output: The program prints the first error message with line number.

Solution

class Stack:
    def __init__(self):
        self.items = []

    def isEmpty(self):
        return self.items == []

    def push(self, item):
        self.items.append(item)

    def pop(self):
        return self.items.pop()

    def peek(self):
        return self.items[len(self.items)-1]

    def size(self):
        return len(self.items)

def main():
    s = Stack()
    file = open(\'Robotinput.txt\', \'r\')
    while 1:
        char = file.read(1)          # read by character
        if char == \'{\' or char == \'[\' or char == \'(\':
            s.push(char)
        elif char == \'}\':
            if s.pop() != \'{\':
                print \"Invalid syntax\"
                break
        elif char == \']\':
            if s.pop() != \'[\':
                print \"Invalid syntax\"
                break
        elif char == \')\':
            if s.pop() != \'(\':
                print \"Invalid syntax\"
                break
        if not char:
            break
    if(s.size()!=0):
        print \"Invalid syntax\"
main()

 A programming language compiler check your programs for syntax errors, but frequently a lack of one symbol (such as missing comment ender */or)) will cause the

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site