簡體   English   中英

python - pyparsing - 如何解析包含元組的函數?

[英]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 添加到我的解析器?”的答案。 問題:

  1. 寫出特征 X 的 pyparsing 表達式。
  2. 使用 runTests() 為功能 X 編寫一些測試字符串並確保它們工作。
  3. 找出它適合 NumericStringParser 的位置。 提示:尋找使用類似物品的地方,以及它們所在的地方。
  4. 使用 Feature X 編寫更多的整體字符串測試。
  5. 將 Feature 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM