Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitd7946a7

Browse files
committed
Add a prefix language generation
1 parent04d769a commitd7946a7

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

‎pyformlang/cfg/cfg.py‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1104,3 +1104,48 @@ def is_normal_form(self):
11041104
"""
11051105
returnall(
11061106
production.is_normal_form()forproductioninself._productions)
1107+
1108+
defget_prefix_language(self):
1109+
"""
1110+
Generates the prefix language of the CFG, i.e., the language of all prefixes of valid words
1111+
Based on https://cs.uwaterloo.ca/~s4bendav/files/CS360S21Lec10.pdf
1112+
"""
1113+
ifself.is_empty():
1114+
returnCFG()
1115+
cfg=self
1116+
ifnotself.is_normal_form():
1117+
cfg=cfg.to_normal_form()
1118+
cfg=cfg.remove_useless_symbols()
1119+
defto_zero(var:Variable):
1120+
returnVariable((var.value,0))
1121+
new_variables=list(cfg.variables)+ [to_zero(var)forvarincfg.variables]
1122+
new_productions=list(cfg.productions)
1123+
forpincfg.productions:
1124+
iflen(p.body)==1:
1125+
# the production is of the form X -> c
1126+
new_productions.append(Production(
1127+
to_zero(p.head),
1128+
p.body
1129+
))
1130+
new_productions.append(Production(
1131+
to_zero(p.head),
1132+
[Epsilon()]
1133+
))
1134+
else:
1135+
# the production is of the form X -> Y Z
1136+
new_productions.append(Production(
1137+
to_zero(p.head),
1138+
[p.body[0],to_zero(p.body[1])]
1139+
))
1140+
new_productions.append(Production(
1141+
to_zero(p.head),
1142+
[to_zero(p.body[0])]
1143+
))
1144+
new_productions.append(Production(cfg.start_symbol, [Epsilon()]))
1145+
new_productions.append(Production(to_zero(cfg.start_symbol), [Epsilon()]))
1146+
returnCFG(
1147+
variables=set(new_variables),
1148+
terminals=set(cfg.terminals)| {Epsilon()},
1149+
productions=new_productions,
1150+
start_symbol=to_zero(cfg.start_symbol),
1151+
)

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp