2013-12-10 18 views
1

我一直试图找出这个问题多个小时,仍然没有运气。我正在编写Python的Connect4作为学校作业,我需要一个函数来检查板子是否已满。Python检查空字符串的2d列表?

这里是我的初始化功能

def __init__(self, width, height): 
    self.width = width 
    self.height = height 
    self.data = [] # this will be the board 

    for row in range(self.height): 
     boardRow = [] 
     for col in range(self.width): 
      boardRow += [' '] 
     self.data += [boardRow] 

再版功能

def __repr__(self): 
    #print out rows & cols 
    s = '' # the string to return 
    for row in range(self.height): 
     s += '|' # add the spacer character 
     for col in range(self.width): 
      s += self.data[row][col] + '|' 
     s += '\n' 

s += '--'*self.width + '-\n' 

for col in range(self.width): 
    s += ' ' + str(col % 10) 
s += '\n' 

return s 

而我有我的isFull功能

def isFull(self): 
# check if board is full 
for row in range(0,(self.height-(self.height-1))): 
    for col in range(0,self.width): 
    if (' ') not in self.data[row][col]: 
     return True 

我要检查和看看有没有这是数据列表中的一个空格。至少我认为这是我的问题,我没有经验过python,所以我可能会误解我的问题。如果有人有任何想法,我很乐意倾听。

+0

那么,你的问题是什么?哪种方法不起作用?它怎么不起作用?并请妥善调整您的代码。另外,这个范围是什么(0,(self.height-(self.height-1)))'?它与'range(0,1)' – justhalf

+0

相同我需要一个函数来检查2D列表中的任何地方是否有空格 – user3067803

+0

您可能想在[CodeReview]上发布代码(http:// codereview.stackexchange.com/)一旦你有它的工作(不与重大错误/错误),并得到一些改进的想法。 – KobeJohn

回答

2

那么如果有空间,这意味着董事会没有满员?

各种版本:

# straightforward but deep 
def is_full(self): 
    for row in self.data: 
     for cell in row: 
      if cell == ' ': 
       return False 
    return True 

# combine the last two 
def is_full(self): # python functions/methods are usually lower case 
    for row in self.data: # no need to index everything like c 
     if any(cell == ' ' for cell in row): # any/all are convenient testers 
      return False # if you find even one, it's done. 
    return True # if you couldn't disqualify it, then it looks full 

# one line, not especially readable 
def is_full(self): 
    return not any(cell == ' ' for row in d for cell in row) 
+0

我真的不能够感谢你。我不是一个程序员,所以我一直试图弄清楚这几个小时,这完美的工作。再次感谢你 – user3067803

+0

太棒了!如果你能正式接受答案,我将不胜感激。周围温暖的模糊。 – KobeJohn

1

您的isFull方法逻辑是不正确。

在您当前的代码中,只要找到非空单元格,就会从isFull返回True。这是不正确的。你应该做相反的事情。

你应该做kobejohn早些时候发布的内容:一旦找到空单元格就返回False

在Python中,如果可能的话,您应该使用Python自然循环,就像在kobejohn所发布的代码中一样。