python pyparsing如何解析包含元组的函数?

2024-04-20 03:01:52 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我在做一个parser,但是程序不解析以元组为参数的函数。例如,当我使用dist函数时,定义如下:

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)))

结果如下:

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

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

如何修改解析器以接受元组函数参数,以便evaluate("dist((5, 2), (3, 4))")返回2.8284271247461903?你知道吗


Tags: orofthe函数lenifdistnot
2条回答

如果您想在python中传递数量可变的参数,则需要使用args关键字。This问题解释了如何做到这一点,但我将从这里的答案复制代码:

  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)

下面是对“如何将特性X添加到解析器”的回答问题:

  1. 为功能X编写pyparsing表达式
  2. 使用runTests()为featurex编写一些测试字符串并确保它们正常工作。你知道吗
  3. 找出它在NumericStringParser中的位置。提示:查找相似项的使用位置和所在位置。你知道吗
  4. 使用featurex对所有字符串编写更多的测试
  5. 将特性X插入解析器并运行测试。确保你以前所有的测试都通过了。你知道吗

如果这个问题对你来说太有挑战性了,那么你要做的就不仅仅是从Google复制粘贴代码了。StackOverflow用于回答特定问题,而不是实际上是CS学期课程主题的广泛问题。你知道吗

相关问题 更多 >