【问题标题】:Showing Type error int object is not subscriptable in the rat in a maze problem that I tried to solved using python在我尝试使用 python 解决的迷宫问题中,显示类型错误 int 对象在老鼠中不可下标
【发布时间】:2020-06-26 07:52:28
【问题描述】:

这是我在迷宫问题中解决老鼠的代码我正在尝试使用 canmoveforward 和 canmovedown 函数的逻辑,但出现类型错误,int object is not subscriptable 我不明白为什么它显示错误

puzzle=[[1,0,0,0],
   [1,1,0,1],
   [0,1,0,0],
   [0,1,1,1]]


sol=[[0,0,0,0],
 [0,0,0,0],
 [0,0,0,0],
 [0,0,0,0]]      
N=4;
def canforward(x,y,arr,N):
  if x==y==N:
    return False
  else:
    for i in range(x+1,N):
      if arr[i][y]==1:
        return True
      return False

def canmovedown(x,y,arr,N):
  if x==y==N:
    return False
  else:
    for i in range(y+1,N):
      if arr[x][i]==1:
        return True
      return False

 def runrat(x,y,arr):
    if x==y==N:
      print(sol)
      return True
    else:
      if canforward(x,y,arr,N):
        sol[x+1][y]=1
        if runrat(x+1,y,N):
          return True
      else:
        sol[x+1][y]=0
        return False
   elif canmovedown(x,y,arr,N):
       sol[x][y+1]=1
       if runrat(x,y+1,N):
          return True
       else:
          sol[x][y+1]=0
          return False
   else:
      return False


 runrat(0,0,puzzle)
 print(sol)

【问题讨论】:

  • 分享错误

标签: python-3.x typeerror backtracking


【解决方案1】:

你的缩进错了,runrat函数里面的条件级别是“if, else, elif”?请正确检查您的代码和网站。

【讨论】:

    【解决方案2】:

    清理缩进后:

    N=4;
    ...
     def runrat(x,y,arr):
    ...
            if runrat(x+1,y,N):
    ...
           if runrat(x,y+1,N):
    

    runrat 函数需要一个列表列表作为它的第三个参数arr,但您传递给它的是一个整数N。我相信这就是您收到“int object is not subscriptable”错误的原因。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多