[ad_1]
最終結果が正しいとしても、2Dlist 内には存在しないことに注意してください。 個別の独立したリストを返しています。返すこれらのリストはリスト内にある必要があることに注意してください。 つまり、最終出力は 2Dlist になるはずです。 この問題を解決して再送信してください。
私が試したこと:
# Compulsory Task 1 # This program takes a grid of # and -, where each # represents a mine and each dash (-)represents a mine-free spot. # Returning a grid, where each dash is replaced by a digit, indicating the number of mines immediately adjacent to the spot. # This functions has data manipulation on how will the grid be displayed def minesweeper(grid): # Firstly we initialise rows and columns row_num = len(grid) column_num = len(grid[0]) #========== New grid is created ======== # "-" are firstly replaced by 0 on this new grid # "#" remain on the grid and is not replaced by any other value new_grid = [[0] * column_num for _ in range(row_num)] hash_count = 0 # Outer loop for rows # The enumerate method takes two arguments, the iterable and the starting for count_row, row in enumerate(grid): # Inner loop for columns for count_column, col in enumerate(row): if col == "#": new_grid[count_row][count_column] = "#" #======== Further manipilation on the new grid # 0's remains on the grid, or either replaced by 1, 2, 3 or 4. # However # remains on the grid else: # Depending on the row count,column count and length of grid # 0's are replaced by a new value if count_row >= 0 and count_row < len(grid)-1: if grid[count_row+1][count_column] == "#": hash_count += 1 if count_row > 0 and count_row <= len(grid)-1: if grid[count_row-1][count_column] == "#": hash_count += 1 if count_column >= 0 and count_column < len(row)-1: if row[count_column+1] == "#": hash_count += 1 if count_column > 0 and count_column <= len(row)-1: if row[count_column-1] == "#": hash_count += 1 # Depending on the row count,column count, length of grid and row # 0's are replaced by a new value if count_row >= 0 and count_row < len(grid)-1 and count_column >= 0 and count_column < len(row)-1: if grid[count_column+1][count_column+1] == "#": hash_count += 1 if count_row >= 0 and count_row < len(grid)-1 and count_column > 0 and count_column <= len(row)-1: if grid[count_row+1][count_column-1] == "#": hash_count += 1 if count_row > 0 and count_row <= len(grid)-1 and count_column >= 0 and count_column < len(row)-1: if grid[count_row-1][count_column+1] == "#": hash_count += 1 if count_row > 0 and count_row <= len(grid)-1 and count_column > 0 and count_column <= len(row)-1: if grid[count_row-1][count_column-1] == "#": hash_count += 1 new_grid[count_row][count_column] = str(hash_count) hash_count = 0 return new_grid grid = [["-", "-", "-", "#", "#"], ["-", "#", "-", "-", "-"], ["-", "-", "#", "-", "-"], ["-", "#", "#", "-", "-"], ["-", "-", "-", "-", "-"]] # Function is called and new grid is displayed for row in minesweeper(grid): print(row)
解決策 1
最後の 2 行を次のように置き換えます。
Python
import pprint
pp = pprint.PrettyPrinter(indent=2)
answer = minesweeper(grid)
pp.pprint(answer)
[ad_2]
コメント