0
a_string = 'abc'

destination = [2, 3]    

edges = { (1, 'a') : [2, 3],
          (2, 'a') : [2],
          (3, 'b') : [4, 3],
          (4, 'c') : [5] }

def make(a_string, destination, edges):
    n = 0
    while n + 1 < len(a_string):
        letter = a_string[n]
        letter2 = a_string[n + 1]
        for d in destination:                              # (1)
            if (d, letter2) in edges:
                for state in edges[(d, letter2)]:
                    destionation.append(state)
            destination.remove(d)
        n += 1                                             # (2)
    return destination

代码返回[],但我希望看到[5],所以我认为问题在于它n意外增加然后进行letter2更改。为什么此代码n在完成for循环(在位置 1)之前递增(在位置 2)?

4

3 回答 3

1

在循环完成之前 n 不会增加。您可能缺少的是 while 循环检查 n+1 而不是 n。

现在编辑我们有更多信息:

问题是您正在从具有未定义行为的迭代器中删除项目。

尝试

for d in destination[:]:

这是整个数组的切片运算符,因此它充当复制构造函数。您现在正在循环一个不同的对象,并且删除应该是安全的。

于 2012-08-29T14:55:20.660 回答
0

您也可以遍历字符串,并且使用index字符串的方法可以获取字符的下一个位置。

结合这两者,您的初始外循环可以简化:

def make(a_string, destination, edges):

    for letter in a_string:
        while a_string.index(letter)+1 < len(a_string):
            next_letter = a_string[a_string.index(letter)+1]

此外,您不应命名变量string,因为它是模块的名称。

于 2012-08-29T15:14:28.947 回答
0

如果在循环结束时不给 n 加 1,则循环条件保持不变,循环将永远执行。它不是在 for 循环中执行,而是在 while 循环体中执行。(缩进决定了一行属于哪个代码块!)

于 2012-08-29T14:50:10.253 回答