usr bin python coding utf-8 import random Грамматика neterm 1P D2P DP

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#!/usr/bin/python
# coding: utf-8
import random
# Грамматика
neterm = {u'S':[(u'1P', u'D2P')], u'DP': [(u'N', u'D2P')], u'D2P':[(u'D', u'NP')], u'1P':[(u'1', u'2P')], u'2P':[(u'DP', u'2')], u'NP':[(u'S'), ('N')]}
term = {u'N':[1,2,3,4,5,6,7,8,9], u'D':[u'-', u'+', u'/', u'*'], u'1':[u'('], u'2':[u')']}
def expression(neterm):
cur = [u'S']
while True:
cur_new = []
for i in range(len(cur)):
if cur[i] in neterm:
cur_new.append(i)
if cur_new:
num = random.choice(cur_new)
seq = random.choice(neterm[cur[num]])
cur.pop(num)
for i in xrange(len(seq)):
cur.insert(num, seq[len(seq)-i-1])
else:
return cur
expr = expression(neterm)
for j in xrange(len(expr)):
expr.insert(j, random.choice(term[expr.pop(j)]))
print ''.join([str(x) for x in expr])