[英]python - pyparsing - How to parse functions containing tuples?
所以我正在制作一個解析器,但該程序不解析具有元組作為參數的函數。 例如,當我使用如下定義的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
?
這是這個和所有未來“如何將功能 X 添加到我的解析器?”的答案。 問題:
如果這個問題對你來說太具有挑戰性了,那么你有更多的學習要做,而不僅僅是從谷歌復制粘貼代碼。 StackOverflow 用於回答特定問題,而不是實際上是 CS 學期課程主題的廣泛問題。
如果您想在 python 中傳入可變數量的參數,則需要使用args
關鍵字。 這個問題解釋了如何做到這一點,但我將從這里的答案中復制代碼:
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.