Search code examples
pythonpython-3.xparsingpyparsing

python - pyparsing - How to parse functions containing tuples?


So I am making a parser, but the program doesn't parse functions that have tuples as arguments. For example, when I use the dist function defined as below:

def dist(p, q):
    """Returns the Euclidean distance between two points p and q, each given as a sequence (or iterable) of coordinates. The two points must have the same dimension."""
    if not isinstance(p, tuple):
        p = p,
    if not isinstance(q, tuple):
        q = q,
    if not p or not q:
        raise TypeError
    if len(p)!=len(q):
        raise ValueError
    return math.sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))

Here is the result:

>> evaluate("dist(5, 2)")
3

>> evaluate("dist((5, 2), (3, 4))")
SyntaxError: Expected end of text, found '('  (at char 4), (line:1, col:5)

How can I modify the parser to accept tuple function arguments, so that evaluate("dist((5, 2), (3, 4))") returns 2.8284271247461903?


Solution

  • Here is the answer to this and all future "how do I add Feature X to my parser?" questions:

    1. Write the pyparsing expression for Feature X.
    2. Write some test strings for Feature X and make sure they work, using runTests().
    3. Figure out where it fits into the NumericStringParser. Hint: look for where similar items are used, and where they reside.
    4. Write some more tests of over-all strings using Feature X.
    5. Insert Feature X into the parser and run your tests. Make sure all your previous tests still pass too.

    If this problem is too challenging for you, then you have more learning to do than to just copy-paste code from Google. StackOverflow is for answering specific questions, not broad questions that are actually the topic of semester courses in CS.