对角元素的差异

时间:2018-09-06 01:31:53

标签: python python-3.x

我有一块4x4的木板:

board=[[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]]

board = [1,0,0,0]
        [0,1,0,0]
        [0,0,1,0]
        [0,0,0,1]

board2= [0,0,1,0]
        [1,0,0,0]
        [0,0,1,0]
        [1,0,0,0]

我必须在此板上进行对角线检查,即如果元素彼此对角线,则应该返回False,否则返回True。

我想到了在其中获取值为'1'的元素的坐标,但没有想到实现其余元素的逻辑。

def diagonal(trialboard):
    coordinates=[]
    for i in range(0,len(trialboard)):
        for j in range(0 ,len(trialboard)):
            if trialboard[i][j]==1:
                a=[i,j]
                coordinates.append(a)

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

我不确定我是否明白你的意思

  

我必须在此板上进行对角线检查,即如果元素彼此对角线,则应该返回False,否则返回True。

如果我没记错,则可以检查第i个子列表的第i个元素是否对角线为1。请参阅:

board=[[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]

然后

def diagonal(trialboard): #I assume trialboard is the list such as "board"...
  if len(trialboard[0])!=len(trialboard) return true #if the matrix is not  
                                                     #square it cannot have a
                                                     #diagonal
   #Here I also assume the sublists all have the same length, but this is just
   #for demonstration

  for i in range(0,len(trialboard)):
       if (trialboard[i][i] !=1) : return true  #is not diagonal (as you specified, 
                                                #returns true)
       if (i==len(trialboard)-1) : return false #it didn't fail until the last element,
                                                #then it is 
                                                #diagonal.

这也是一种更有效的方法,因为您不需要像在两个嵌套的for语句中那样遍历每个[i] [j]对。您只需检查对角线值即可。