首页 > 解决方案 > 我怎么知道两件事是否可以互相看到?

问题描述

我怎么知道是否有两个可以垂直或水平看到对方的“L”?这是一个基于网格的问题。这是我目前拥有的代码,但它似乎不起作用。

def sight(board):
  lst = []
  for line in board:
    linelst = []
    for char in line.strip():
      linelst.append(char)
    lst.append(linelst)
  counter=-1
  count=-1
  
  for i in lst:
    
    count+=1
    counter = -1
    for item in i:
      counter+=1
      if item == 'L':
        numlstings = ['0','1','2','3','4']
        for inter in range(1, len(lst)):
          for inte in range(1,len(i)):
            try:
              
              
              
              if lst[count+inte][counter] == 'L' and count+inte > -1 and count+inte < len(lst) and count+inte > count:
                


                return 'unhappy'
              if lst[count-inte][counter] == 'L' and count-inte > -1 and count-inte < len(lst) and count-inte < count:
                
                
                return 'unhappy'
              if lst[count][counter+inter] == 'L' and counter+inter > -1 and counter+inter < len(i) and counter+inter<counter:
                
                return 'unhappy'
              if lst[count][counter-inter] == 'L' and counter-inter > -1 and counter-inter < len(i) and counter-inter>counter:
                
                return 'unhappy'

              if lst[count+inte][counter] == 'X' or lst[count+inte][counter] in numlstings:
                break;
              if lst[count-inte][counter] == 'X' or lst[count-inte][counter] in numlstings:
                break;
              if lst[count][counter+inter] == 'X' or lst[count][counter+inter] in numlstings:
                break;
              if lst[count][counter-inter] == 'X' or lst[count][counter-inter] in numlstings:
                break;
            except IndexError:
              break;
                
              
  return 'happy'

如果它可以在同一行或列中看到另一个“L”,而没有“X”或数字侵入它,我希望这段代码返回不愉快。否则,如果它看不到 L,它应该返回快乐。

一个这样的委员会是:

'......X.L.
.X..X...X.
L........L
X.....L...
....XX..X.
...LXX....
.X......L.
L.........
.......LXL
..LXL.....'.strip().split('\n')

这应该返回不愉快,但我的代码返回快乐。我还必须测试不同的板。

标签: python-3.x

解决方案


推荐阅读