-1

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?

TheOneMusic
  • 1,776
  • 3
  • 15
  • 39

2 Answers2

2

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.

PaulMcG
  • 62,419
  • 16
  • 94
  • 130
  • 2
    Parsing of tuples is actually covered in several examples on the pyparsing GitHub repo.https://github.com/pyparsing/pyparsing. – PaulMcG Aug 08 '19 at 10:39
1

If you would like to pass in a variable number of parameters in python, you will need to use the args keyword. This question explains how to do that, but I'll copy the code from the answer here:

  print "I was called with", len(arg), "arguments:", arg

>>> manyArgs(1)
I was called with 1 arguments: (1,)
>>> manyArgs(1, 2,3)
I was called with 3 arguments: (1, 2, 3)
NerdyGinger
  • 406
  • 7
  • 13
  • 2
    @TheOneMusic: please don't do that. If you want to ask a specific question about specific code, put the specific code into your question (as code-formatted text, not as an image nor a link), ideally having reduced it to a [mre]. Once the question is asked, don't modify it -- or, if you do, expect people who answered (or were working on answers) to the original question to get annoyed and quite possibly become reluctant to work on your future questions. SO is not an interactive debugging/code-writing assistance service. It seeks to be a repository of useful answers to specific questions. – rici Aug 08 '19 at 00:33