康威的生命游戏指数错误

时间:2016-11-11 22:27:41

标签: python-2.7 for-loop

所以我必须用5条规则来做康威的生命游戏:

  1. 活动邻居少于两个的单元格
  2. 有超过3个活邻居的单元格
  3. 一个已经死亡且正好有3个活着的邻居的牢房正在栩栩如生
  4. 所有边缘单元格保持为0
  5. 所有其他单元格保持其状态
  6. 示例:

    >>> A = [ [0,0,0,0,0],
          [0,0,1,0,0],
          [0,0,1,0,0],
          [0,0,1,0,0],
          [0,0,0,0,0]]
    
    >>> printBoard(A)
    00000
    00100
    00100
    00100
    00000
    
    >>> A2 = next_life_generation( A )
    >>> printBoard(A2)
    00000
    00000
    01110
    00000
    00000
    
    >>> A3 = next_life_generation( A2 )
    >>> printBoard(A3)
    00000
    00100
    00100
    00100
    00000
    and so on... .
    

    注意,next_life_generation(A)返回一个新的板,所以我可以继续将A重新绑定到每一代 到目前为止,这是我的代码:

    def countNeighbors(row, col, A):
    count = 0
    for row in range(len(A) - 1, len(A) + 2):
        for col in range(len(A) - 1, len(A) + 2):
            if A[row][col] == 1:
                count += 1
    return count
    
    def next_life_generation(A):
        for row in range(1, len(A) - 1):
            for col in range(1, len(A[0]) - 1):
                if A[row][col] == 0 and countNeighbors(row, col, A) == 3:
                    A[row][col] = 1
                if countNeighbors(row, col, A) < 2:
                    A[row][col] = 0
                elif countNeighbors(row, col, A) > 3:
                    A[row][col] = 0
        return A
    

    我的问题是我得到了这个错误:

        Traceback (most recent call last):
      File "<pyshell#10>", line 1, in <module>
        A = next_life_generation(A)
      line 88, in next_life_generation
        if countNeighbors(row, col, A) < 2:
      line 79, in countNeighbors
        if A[row][col] == 1:
    IndexError: list index out of range
    

    如果有人能帮助我,我将不胜感激!

0 个答案:

没有答案