无法弄清楚为什么在Python

时间:2015-07-31 21:32:40

标签: python

对于家庭作业,我正在进行各种测试,无法解决以下代码:

grammar = [ 
    ("exp", ["exp", "+", "exp"]),
    ("exp", ["exp", "-", "exp"]),
    ("exp", ["(", "exp", ")"]),
    ("exp", ["num"]),
    ]


def expand(tokens, grammar):
    result = []
    for pos in range(len(tokens)):
        print "pos = " + str(pos)
        rulec = 0
        for rule in grammar:
            # hmmmm
            print "rule = " + str(rule)
            if tokens[pos] == rule[0]:
                print "token matches rule!"
                if pos == 0:
                    for i in range(1,len(rule)):
                        result.append(rule[i])
                else:
                   for i in range(1,len(rule)):
                        result[rulec].extend(rule[i])                
            else:
                print "token doesn't match rule"
                if pos == 0:
                    print "First instance"
                    result.append([tokens[pos]])
                else:
                    print "Appending..."
                    #result[rulec].extend(copy.copy(tokens[pos]))
                    result[rulec].extend('abc')
            print "result so far = " + str(result)
            print "grammar so far = " + str(grammar)
            rulec += 1
    print "result = " + str(result)
    for i in result:
        yield i

depth = 1
utterances = [["exp","a","exp"]]
for x in range(depth):
    for sentence in utterances:
        utterances = utterances + [ i for i in expand(sentence, grammar)]

for sentence in utterances:
    print sentence

如果我执行上述操作,我希望得到这个:

['exp', 'a', 'exp']
['exp', '+', 'exp', 'a', 'b', 'c', 'exp', '+', 'exp']
['exp', '-', 'exp', 'a', 'b', 'c', 'exp', '-', 'exp']
['(', 'exp', ')', 'a', 'b', 'c', '(', 'exp', ')']
['num', 'a', 'b', 'c', 'num']

然而,我实际上得到了这个:

['exp', 'a', 'exp']
['exp', '+', 'exp', 'a', 'b', 'c', 'exp', '+', 'exp', 'a', 'b', 'c']
['exp', '-', 'exp', 'a', 'b', 'c', 'exp', '-', 'exp', 'a', 'b', 'c']
['(', 'exp', ')', 'a', 'b', 'c', '(', 'exp', ')', 'a', 'b', 'c']
['num', 'a', 'b', 'c', 'num', 'a', 'b', 'c']

出于某种原因,我无法理解,当我在[exp]之间传递一个普通字符串(例如'a'),如[[“exp”,“a”,“exp”]],字符串被添加到最后。我把一堆打印语句放入其中,看起来一旦pos == 1并且代码附加到结果列表,它也会附加到语法列表中。然而,对于我的生活,我无法弄清楚为什么。我没有看到这种联系。

如果这有帮助,当我运行代码时 - 问题出现在这里:

pos = 1
rule = ('exp', ['exp', '+', 'exp'])
token doesn't match rule
Appending...
result so far = [['exp', '+', 'exp', 'a'], ['exp', '-', 'exp'], ['(', 'exp', ')'], ['num']]
grammar so far = [('exp', ['exp', '+', 'exp', 'a']), ('exp', ['exp', '-', 'exp']), ('exp', ['(', 'exp', ')']), ('exp', ['num'])]
  1. 问题#1 - 结果不应该在结尾处有额外的'a' 第一个嵌入列表
  2. 问题#2 - 为什么要修改语法?
  3. 我错过了什么? --Jim

1 个答案:

答案 0 :(得分:1)

问题在于你是在迭代话语并同时附加到话语上。尝试这样的事情:

sentences = []
for x in range(depth):
  for sentence in utterances:
    sentences = sentences + [ i for i in expand(sentence, grammar)]

for sentence in sentences:
  print sentence