Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add count_atoms to GrammaticalExpression #48

Merged
merged 2 commits into from
Nov 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/tests/test_grammar.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@ def test_meaning(self):
def test_length(self):
parsed_expression = TestGrammar.grammar.parse(TestGrammar.geq2_expr_str)
assert len(parsed_expression) == 5

def test_atom_count(self):
parsed_expression = TestGrammar.grammar.parse(TestGrammar.geq2_expr_str)
assert parsed_expression.count_atoms() == 3

def test_yield(self):
parsed_expression = TestGrammar.grammar.parse(TestGrammar.geq2_expr_str)
Expand Down
6 changes: 6 additions & 0 deletions src/ultk/language/grammar.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,12 @@ def to_dict(self) -> dict:
if self.children:
the_dict["children"] = tuple(child.to_dict() for child in self.children)
return the_dict

# Following function counts the total number of atoms / leaf nodes, as opposed to __len__, which counts all nodes
def count_atoms(self):
if self.children is None:
return 1
return sum(child.count_atoms() for child in self.children)

@classmethod
def from_dict(cls, the_dict: dict, grammar: "Grammar") -> "GrammaticalExpression":
Expand Down