我是新来python。我试图写一个代码,以从文本文件输入像
6 6
* o o o o *
o o * o o o
o o * o o *
o o * o o o
o o o o * o
o o o o o o
和计数"*"的每个string附近的数量和更新与新的计数每个string这样的:
6 6
* 2 1 1 1 *
1 3 * 2 2 2
0 3 * 3 1 *
0 2 * 2 2 2
0 1 1 2 * 1
0 0 0 1 1 1
和上output.txt的更新此。到现在为止我的代码正在输入,并提供行,列和矩阵但只要我进入list来算,它无法给错误
if matrix[num_rows][num_columns][1] == "x":
IndexError: list index out of range
我的代码片段:
def parse_in(input_name):
list_of_lists = []
with open(input_name,"r") as f:
for line in f:
with open(input_name) as f:
num_rows, num_columns = [int(x) for x in next(f).split()]
lines = f.read().splitlines()
# in alternative, if you need to use the file content as numbers
matrix = []
print(lines)
for x in lines:
matrix.append(x.split(' '))
print(matrix)
return matrix, num_rows, num_columns
def detector(matrix, num_rows, num_columns):
mine_count = 0
# For every every space around the square, including itself
for r in range(num_rows):
for c in range(num_columns):
# If the square exist on the matrix
if 0 <= num_rows + r <= 2 and 0 <= num_columns + c <= 2:
# If the square contains a mine
if matrix[r][c] == "*":
# Raise the mine count
mine_count = mine_count + 1
# If the original square contains a mine
if matrix[r][c] == "*":
print(mine_count)
# Lower the mine count by 1, because the square itself having a mine shouldn't be counted
mine_count = mine_count - 1
print(mine_count)
return mine_count
def parse_out(output_name, my_solution):
pass
def my_main(input_name, output_name):
# 1. We do the parseIn from the input file
lines, num_rows, num_columns = parse_in(input_name)
# 2. We do the strategy to solve the problem
my_solution = detector(lines, num_rows, num_columns)
# 3. We do the parse out to the output file
parse_out(output_name, my_solution)
if __name__ == '__main__':
# 1. Name of input and output files
input_name = "input_2.txt"
output_name = "output.txt"
# 2. Main function
my_main(input_name, output_name)
分析解答
在创建矩阵,你不需要两个循环。您可以在读取文件中的循环直接建立矩阵。你也不需要多次打开该文件。
def parse_in(input_name):
matrix = []
with open(input_name,"r") as f:
num_rows, num_columns = [int(x) for x in next(f).split()]
for line in f:
matrix.append(line.split(' '))
return matrix, num_rows, num_columns
你并不需要num_rows
和num_columns
传递给detector()
function。不同语言,如C,Python知道列表的长度,这样你就可以刚过直接list元素循环。你也可以使用enumerate()
得到尽可能你循环索引。
当旁边的一个方形计数的地雷数量,你只需要循环从r-1
到r+1
和c-1
到c+1
。而你需要这个循环之前mine_count
设置为0
。
def detector(matrix):
result = []
for r, row in enumerate(matrix):
result_row = []
for c, cell in enumerate(row):
if cell == "*":
result_row.append(cell)
else:
mine_count = 0
for x in range(c-1, c+2):
for y in range(r-1, r+2):
if 0 <= x < len(row) and 0 <= y < len(matrix) and matrix[x][y] == "*":
mine_count += 1
result_row.append(str(mine_count))
result.append(result_row)
return result