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
改变。
为什么这个代码在完成for
循环(在位置1)之前增加n
(在位置2)?你知道吗
您也可以在字符串上迭代,并且使用字符串的
index
方法可以获取字符的下一个位置。你知道吗将这两者结合起来,可以简化初始外循环:
此外,您不应该将变量命名为
string
,因为它是模块的名称。你知道吗在循环完成之前,n不会递增。 您可能缺少的是while循环检查n+1而不是n
编辑现在我们有更多信息:
问题是您正在从具有未定义行为的迭代器中删除项。你知道吗
试试看
这是整个数组上的切片运算符,因此它充当复制构造函数。 您现在正在另一个对象上循环,删除应该是安全的。你知道吗
如果在循环末尾不加1到n,循环条件保持不变,循环将永远执行。它不是在for循环中执行的,而是在while循环体中执行的。(缩进决定一行属于哪个代码块!)你知道吗
相关问题 更多 >
编程相关推荐