The following python code generates mathematical expressions using simple (slightly modified) generative grammar.
def gen(grammar, N, N_max, S):
if N > N_max:
return []
result = []
terminal = True
for rule in grammar:
for i in range(0, len(S)):
ch = S[i]
if ch == rule[0]:
Snew = S[0:i] + rule[1] + S[(i + 1):len(S)]
result = result + gen(grammar, N + 1, N_max, Snew)
terminal = False
if terminal:
return [S]
return list(set(result))
grammar = [
["S", "(S + S)"],
["S", "(S * S)"],
["S", "(S - S)"],
["S", "(-S)"],
["S", "x"],
["S", "y"],
["S", "z"],
["S", "0"],
["S", "1"],
["S", "2"],
["S", "3"],
]
for f in gen(grammar, 0, 4, "S"):
print f
Output:
(y * (-0))
(3 + 1)
((-z) - 2)
((-y) * z)
(-(3 - x))
((-3) - z)
(3 * 1)
...
(-(2 * 2))
Žádné komentáře:
Okomentovat