所以我在做一个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
?你知道吗
如果您想在python中传递数量可变的参数,则需要使用
args
关键字。This问题解释了如何做到这一点,但我将从这里的答案复制代码:下面是对“如何将特性X添加到解析器”的回答问题:
如果这个问题对你来说太有挑战性了,那么你要做的就不仅仅是从Google复制粘贴代码了。StackOverflow用于回答特定问题,而不是实际上是CS学期课程主题的广泛问题。你知道吗
相关问题 更多 >
编程相关推荐