2d数组Python:列表索引超出范围

2024-04-27 01:11:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python编程新手,我正试图编写代码来检查DFA(确定性有限自动机)是否有空语言。在

我使用二维数组来存储DFA的状态。 在执行代码时,我总是让列表索引超出范围。我该怎么解决这个问题?在

下面是代码

top=-1
count=0
n=int(input("\nEnter the no of states"))
mat=[[]]
b=[]
print("\nEnter the transition table")
for i in range(0,n):
   for j in range(0,n):
    mat.append(input())
finalState=input("\nEnter the final state:")
startState=input("\nEnter the start state:")      

for i in range(0,n):
   for j in range(0,n):
      if mat[i][j]:
        b[++top]=j
for k in range(top):
      if b[k]==finalState:
      count+=1
if count>0:
print("\nLanguage is  not empty")
else:
print("\nLanguage is empty")

Tags: the代码inforinputiftopcount
1条回答
网友
1楼 · 发布于 2024-04-27 01:11:57

当你制作一张2x2的桌子时,你希望mat是[[1,2],[3,4]],但你现在得到的是[[],1,2,3,4]。在

相反,请尝试:

mat = []
for i in range(n):
    row = []
    for j in range(n):
        row.append(input())
    mat.append(row)

另外,Python没有“++”运算符,因此b[++top]=j与{}相同。如果您想增加top,那么在使用它来索引列表之前,必须在它自己的行上执行该操作。在

除此之外,b没有元素,因此以任何方式索引它都会导致崩溃。如果您试图通过添加新项来增加b的大小,请使用append。那么您根本不需要top变量。在

^{pr2}$

相关问题 更多 >