1

I'm trying to code a little script that checks whether a file passed as a command line parameter is well or badly parenthesized.

I've created an exception to handle the functions stop point but can not seem to raise it properly.

When I test the code in a Python interpreter, it seems to work (ie it recognizes it should the raise the exception, but when I test my file with the sample files I have (that are badly parenthesized), it still prints out that it was successfully checked

Do you have any ideas ?

Best,

Code :

import sys
from stack import *


class BracketException(Exception) :
    """
    Exception qui gère les problèmes de parenthesage : mauvaise parenthèse,
    mauvais placement etc...
    """

    def __init__(self, char, lineNumber, charNumber) :
        self.char = char
        self.lineNumber = lineNumber
        self.charNumber = charNumber

    def __str__(self) :
        return(self.char + " at line " + str(self.lineNumber) + " char " + str(self.charNumber))


def checker(file) :
    lineNumber = 1
    charNumber = 1

    stacked = Stack()
    openers = ["(", "[", "{"]
    closers = [")", "]", "}"]

    inChannel = open(file, "r")

    for line in file :
        for char in line :
            if char in openers :
                stacked.push([char, lineNumber, charNumber])
                print(stacked.top())
            elif char in closers :
                try :
                    if openers[closers.index(char)] == stacked.top()[0] :
                        stacked.pop()
                    else :
                        raise BracketException(char, lineNumber, charNumber)
                except StackEmptyError :
                    raise BracketException(char, lineNumber, charNumber)

            charNumber += 1
        charNumber = 1
        lineNumber += 1

    inChannel.close()

    if not stacked.is_empty() :
        raise BracketException(stacked.top()[i] for i in range(3))

def __main__() :

    try :
        fichier = sys.argv[1]
        checker(fichier)
        print("it's checked !")
    except BracketException as ex :
        print(ex)
    except IndexError :
        print("Wrong number of parameters")
    except Exception as e :
        print(e)

if __name__ == "__main__" :
    __main__()
2
  • 1
    Can you show one of your sample files that fails to produce an exception? Commented Oct 29, 2018 at 21:33
  • Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation, as suggested when you created this account. Minimal, complete, verifiable example applies here. We cannot effectively help you until you post your MCVE code and accurately describe the problem. We should be able to paste your posted code into a text file and reproduce the problem you described. Commented Oct 29, 2018 at 21:35

1 Answer 1

3

You are iterating over the given file name, not the created filehandle. File names probably have no unbalanced brackets in them, hence no exception.

def checker(file) :
    lineNumber = 1
    charNumber = 1

    stacked = Stack()
    openers = ["(", "[", "{"]
    closers = [")", "]", "}"]

    inChannel = open(file, "r")  # file handle is inChannel

    for line in file :  #  iterating over file name, not file handle

You should switch to

with open(file, "r") as inChannel:
    for line in inChannel :

to make sure to close the file even if you get exceptions thrown - its the prefered way of file handling, see docs.python.org - reading and writing files


I am unable to test this (no stack module - if needed I use lists for that), but this should be faster:

def checker(filename) :
    lineNumber = 1
    charNumber = 1

    stacked = Stack()

    openers = set( "{[(")  # sets are better suited for test of "in"
    closers = set( "}])")  # same

    # mapping between closing bracket at hand and what should be on the stack
    # also faster then .index()ing into a list
    open_for_close = { ")":"(","}":"{","]":"[" }

    with open(filename, "r") as f:
        for line in f:            # iterate over the filehandle 
            for char in line:
                if char in openers:
                    stacked.push([char, lineNumber, charNumber])
                    print(stacked.top())
                elif char in closers:
                    try :
                        if open_for_close[char] == stacked.top()[0] :
                            stacked.pop()
                        else :
                            raise BracketException(char, lineNumber, charNumber)
                    except StackEmptyError :
                        raise BracketException(char, lineNumber, charNumber)
                charNumber += 1
            charNumber = 1
            lineNumber += 1

    if not stacked.is_empty() :
        raise BracketException(stacked.top()[i] for i in range(3))
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this is really helpful !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.