Skip to content

Commit 80528f5

Browse files
committed
Move is_recursive() test to top-level grammar module
1 parent 6223afd commit 80528f5

File tree

2 files changed

+11
-8
lines changed

2 files changed

+11
-8
lines changed

nltk/grammar.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
# Jason Narad <[email protected]>
77
# Peter Ljunglöf <[email protected]>
88
# Tom Aarsen <>
9+
# Eric Kafe <[email protected]>
910
# URL: <https://www.nltk.org/>
1011
# For license information, see LICENSE.TXT
1112
#
@@ -304,6 +305,9 @@ def rhs(self):
304305
"""
305306
return self._rhs
306307

308+
def is_recursive(self):
309+
return self.lhs() in self.rhs()
310+
307311
def __len__(self):
308312
"""
309313
Return the length of the right-hand side.
@@ -605,6 +609,12 @@ def productions(self, lhs=None, rhs=None, empty=False):
605609
if prod in self._rhs_index.get(rhs, [])
606610
]
607611

612+
def is_recursive(self):
613+
for prod in self.productions():
614+
if prod.is_recursive():
615+
return True
616+
return False
617+
608618
def leftcorners(self, cat):
609619
"""
610620
Return the set of all nonterminals that the given nonterminal

nltk/parse/generate.py

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,6 @@
1414
from nltk.grammar import Nonterminal
1515

1616

17-
def is_recursive(grammar):
18-
for prod in grammar.productions():
19-
if prod.lhs() in prod.rhs():
20-
return True
21-
return False
22-
23-
2417
def generate(grammar, start=None, depth=None, n=None):
2518
"""
2619
Generates an iterator of all sentences from a CFG.
@@ -34,7 +27,7 @@ def generate(grammar, start=None, depth=None, n=None):
3427
if not start:
3528
start = grammar.start()
3629
if depth is None:
37-
if is_recursive(grammar):
30+
if grammar.is_recursive():
3831
# This seems to be an almost maximal safe default with Python 3:
3932
depth = (sys.getrecursionlimit() // 3) - 3
4033
else:

0 commit comments

Comments
 (0)