[2021-Fall] Lab12 of CS61A of UCB

Regular Expressions

Q1: Calculator Ops

Write a regular expression that parses strings written in the 61A Calculator language and returns any expressions which have two numeric operands, leaving out the parentheses around them.

def calculator_ops(calc_str):
"""
Finds expressions from the Calculator language that have two
numeric operands and returns the expression without the parentheses.
"""
return re.findall(r'[+\-*/] \d+ \d+', calc_str)


BNF

Q3: Linked List BNF

In this problem, we're going to define a BNF that parses integer Linked Lists created in Python. We won't be handling Link.empty.

For reference, here are some examples of Linked Lists:

Your implementation should be able to handle nested Linked Lists, such as the third example below.

• Link(2)
• Link(12, Link(2))
• Link(5, Link(7, Link(Link(8, Link(9)))))

link: "Link(" link_first ")" | "Link(" link_first "," link_rest ")"

%ignore /\s+/
%import common.NUMBER


Q4: Tree BNF

Now, we will define a BNF to parse Trees with integer leaves created in Python.

Here are some examples of Trees:

Your implementation should be able to handle Trees with no branches and one or more branches.

• Tree(2)
• Tree(6, [Tree(1), Tree(3, [Tree(1), Tree(2)])])

1. tree_node: 可以是只有一个节点的树, 也可以是有结点还有分支的树, 注意分支可以有任意个(包括 0), 所以我们可以用正则表达式中的 +
2. ?label: 就是数字, 直接用 NUMBER 即可
3. branches: 可以是只有一个节点, 或者有多个节点(此时我们要把 , 号匹配进去)
tree_node: "Tree(" label ")" | "Tree(" label "," branches* ")"
?label: NUMBER
branches: "[" tree_node "]" | "[" tree_node "," tree_node+ "]"

%ignore /\s+/
%import common.NUMBER

posted @ 2022-03-02 12:59  MartinLwx  阅读(392)  评论(0编辑  收藏  举报