題目:
範例輸入/輸出:
code:
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 18 23:01:46 2023
@author: SavingKing
"""
# 读取第一行并解析行数
first_line = input("请输入rows和columns,用空格分隔(例如 '4 7'):\t")
rows, cols = map(int, first_line.split())
#4 , 7
# 根据行数读取后续的每一行
data = []
for i in range(rows):
row_data = input(f"请输入第 {i+1} row的数据:\t")
data.append(row_data)
# 现在 'data' 变量包含了所有输入的行
data2D = [strr.split() for strr in data]
import pandas as pd
import numpy as np
df = pd.DataFrame(data2D)
"""
0 1 2 3 4 5 6
0 0 0 0 1 0 0 0
1 0 0 1 1 1 0 0
2 0 1 1 1 1 1 0
3 1 1 1 1 1 1 1
df.shape
Out[129]: (4, 7)
type(df[0][0])
Out[130]: str
"""
zeros = np.zeros(shape = df.shape)
"""
array([[0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0.]])
"""
df_new = pd.DataFrame(zeros).astype(str)
lisCol = df.columns.tolist()
r,c = df.shape
#4 , 7
#四邊的Series
ser0 = df[0]
ser6 = df[ c-1 ]
ser_0row = df.iloc[0,:]
ser_3row = df.iloc[r-1,:]
bool_mask = ser0 == "1"
df_new.loc[bool_mask, 0] = '*'
bool_mask = ser0 == "0"
df_new.loc[bool_mask, 0] = ' '
bool_mask = ser6 == "1"
df_new.loc[bool_mask, c-1] = '*'
bool_mask = ser6 == "0"
df_new.loc[bool_mask, c-1] = ' '
bool_mask = ser_0row == "1"
df_new.iloc[0, bool_mask] = '*'
bool_mask = ser_0row == "0"
df_new.iloc[0, bool_mask] = ' '
bool_mask = ser_3row == "1"
df_new.iloc[r-1, bool_mask] = '*'
bool_mask = ser_3row == "0"
df_new.iloc[r-1, bool_mask] = ' '
for rr in range(1,r-1):
for cc in range(1,c-1):
if df.iloc[rr, cc] == '1' and (
df.iloc[rr, cc-1] == '0' or
df.iloc[rr, cc+1] == '0' or
df.iloc[rr-1, cc] == '0' or
df.iloc[rr+1, cc] == '0'):
df_new.iloc[rr, cc] = "*"
else:
df_new.iloc[rr,cc] = " "
print(df_new.to_string(index=False, header=False))
輸出結果:
推薦hahow線上學習python: https://igrape.net/30afN
看起來是DataFrame預設就有空白
排列起來不像題目這麼緊密
用雙層for迴圈讀取DF的每一個value
code:
for rr in range(r):
for cc in range(c):
print(df_new.iloc[rr,cc],end="")
print() # 在每行的末尾添加一个换行符
輸出結果:
看起來輸出跟答案一樣
但檢查結果就是
答案錯誤!
將input() 中的提示文字刪除後
通過測試
推薦hahow線上學習python: https://igrape.net/30afN
近期留言