0

I'm automating our daily stuff .Here my code takes absolute path of a directory as input. It read each file in the directory which is sorted by file name. and then it Concatenate the content of each file to form a string.The final concatenated string needs to get validated. If string is valid it will yield true else false if it is invalid expression.I'm thinking valid expression : "( a+ b ) * c + (d /e )', I Invalid expression : "( a + b ".

This is below code that was being used to do the stuff.

from math import *
import os
import glob

Path = os.path.abspath("mydir/myfile.txt")
files = glob.glob(Path)
for name in files:
    try:
        with open(name) as f:
            s+=f.read()
            sys.stdout.write(s)
    except IOError as exec:
        if exc.errno != errno.EISDIR:
            raise

def validateSyntax(a):
    functions = {'__builtins__': None}
    variables = {'__builtins__': None}
    functions = {'acos': acos,
        'asin': asin,
        'atan': atan,
        'atan2': atan2,
        'ceil': ceil,
        'cos': cos,
        'cosh': cosh,
        'degrees': degrees,
        'exp': exp,
        'fabs':fabs,
        'floor': floor,
        'fmod': fmod,
        'frexp': frexp,
        'hypot': hypot,
        'ldexp': ldexp,
        'log': log,
        'log10': log10,
        'modf': modf,
        'pow': pow,
        'radians': radians,
        'sin': sin,
        'sinh': sinh,
        'sqrt': sqrt,
        'tan': tan,
        'tanh': tanh}

    variables = {'e': e, 'pi': pi}

    try:
        eval(s,variables, functions)
    except (SyntaxError, NameError, ZeroDivisionError):
        return False
    else:
        pass
Eugene
  • 1,539
  • 12
  • 20
  • Please fix the indentation in your code – inspectorG4dget Nov 06 '16 at 15:08
  • What is the question here? – UnholySheep Nov 06 '16 at 15:10
  • The problem is after the concatenation of the content of each file to form a string final concatenated string needs to be validated.for string validation check I have written a custom interpreter in which expression is getting validated. But it's not working. – Michael Atwood Nov 06 '16 at 15:12
  • *"But it's not working."* Doesn't tell us anything useful. What is happening (e.g.: do you get an error, wrong output, ...). – UnholySheep Nov 06 '16 at 15:17
  • It's giving wrong output when I put the valid expression it's unable to recognise it. – Michael Atwood Nov 06 '16 at 15:22
  • Fix your indentation. Give sample input. Give actual output. Give desired output. Give full trace back if you get an error. Or, get no answer. – Mark Tolonen Nov 06 '16 at 15:58
  • Sample input: (a+b)*c+(d/e) desired output :- true Sample input :- (a+b. desired output:- false – Michael Atwood Nov 06 '16 at 16:25
  • I threw up a little in my mouth, sorry guys... but.. double spacing...?.... .... – Eugene Nov 06 '16 at 16:33
  • @Eugene:-which double spacing,if it's in code that might be due to fast typing. – Michael Atwood Nov 06 '16 at 16:41
  • OK much better. I've also read your question. The best answer to that is to not do it yourself. There are a lot of similar functions and algorithms that already do this and will be much better than anything you or I could code (unless one of us has a tremendous amount of experience in dealing with such problems, in which case, touche). I think the answer is JFGI, which I will quickly do now for you. – Eugene Nov 06 '16 at 16:44
  • Oh, double spacing means an empty line after each line... I'm one of those slightly OCD, neat types, so apologies for my reaction! – Eugene Nov 06 '16 at 16:46
  • LMFAO hey look I found the code that I spent 2 mins tiding up... http://stackoverflow.com/questions/4887627/math-syntax-checker-written-in-python – Eugene Nov 06 '16 at 16:48
  • Dude, I've tried all types of tricks but I do not know why the output is coming wrong. – Michael Atwood Nov 06 '16 at 16:52
  • I'm writing an answer for you. – Eugene Nov 06 '16 at 16:53
  • Thank you.I wish your solution might work. – Michael Atwood Nov 06 '16 at 17:08

1 Answers1

1

OK I will delete if this gets any down-votes, but I really think this is the actual answer to the proposed question.

Firstly, welcome to SO and don't be put of by anyone who may upset you. We all want to help, and we know you're learning. So am I. However, you do have to reciprocate, and this is done by typing out your question neatly, methodically, and in a way that shows you've spent a non-negligible amount of time working on it. This means including:

  • A clear description of your input and desired output
  • Any specification that would help us minimize the amount of time spent guessing
  • Code examples of what you've attempted (that actually run)
  • Reasons (proof, i.e. stacktraces) as to why they are not working
  • What you think the next steps are

I am probably reciting the SO welcome page or something... ANYWAY, I have tidied up your code for you, and did a quick Google search to give you some ideas.

Firstly, DO NOT use exec to solve this problem. Not because it's "dangerous" , but because it is unnecessary. It'll be much slower too. Let's stick to character processing.

After a 90 second Google search (mathematical expression "validator" python), I would use http://codegists.com/snippet/python/math-expression-syntax-validator-of-parentheses-in-python-3

For something more complex, this looks good http://effbot.org/zone/simple-top-down-parsing.htm

Now where you go from there, you would need to provide a spec for. Hope At least some of this helps :)

Eugene
  • 1,539
  • 12
  • 20
  • I appreciate your quick help the expression in codegists.com differs from the above problem. – Michael Atwood Nov 06 '16 at 17:20
  • Looking again at your question, what exactly is the content of an example file that you'd be concatenating? Is a mathematical expression validator actually what you need? See --- the age-old SO game of a quintillion questions :D – Eugene Nov 06 '16 at 17:21
  • Oh, apologies... Well, you could also look at the full-blown evaluators like pyparsing or symfony, or write it yourself (basically an LR parser), I'd do it for you if I knew what you needed... – Eugene Nov 06 '16 at 17:24
  • The expression are mathematical and can be in many forms when concatenation happens from different files so apart from parenthesis the operators also needs the care.:D We need to have custom interpreter to do that. – Michael Atwood Nov 06 '16 at 17:26
  • Of course, although to a computer, the hardest part is indeed the parenthesis, once those are validated, it's fairly trivial to ensure a number sandwich filled with operators. Why not build one yourself? Or GOOGLE IT! http://stackoverflow.com/a/2596378/2178980 – Eugene Nov 06 '16 at 17:29
  • Or, if you CBA to convert that to Python, and really want to copy and paste, how about http://stackoverflow.com/a/2371789/2178980 (note that, this will be slower, and somewhat insecure, but I assume you're not worried about either). – Eugene Nov 06 '16 at 17:32
  • Now THIS guy knows how to write a question! http://stackoverflow.com/questions/34106484/evaluating-a-mathematical-expression-function-for-a-large-number-of-input-valu?rq=1 – Eugene Nov 06 '16 at 17:35
  • He has mixed numpy and py py parser in it – Michael Atwood Nov 06 '16 at 17:40
  • Yup, I read it. – Eugene Nov 06 '16 at 17:42