Python TQC考題706: 整數檔案讀寫;使用str type 排序會出現什麼問題?

加入好友
加入社群
Python TQC考題706: 整數檔案讀寫;使用str type 排序會出現什麼問題? - 儲蓄保險王
Python TQC考題706: 整數檔案讀寫;使用str type 排序會出現什麼問題? - 儲蓄保險王

範例輸入/輸出:

Python TQC考題706: 整數檔案讀寫;使用str type 排序會出現什麼問題? - 儲蓄保險王

code:

# -*- coding: utf-8 -*-
"""
Created on Mon Nov 20 21:34:48 2023

@author: SavingKing

"""
lis_input=[]
for i in range(4):
    lis_input.append(input())
#['10', '35', '60', '85']

lis_input = [strr+"\n" for strr in lis_input]

with open("read.txt","r") as f:
    lis_read = f.readlines()
#['59\n', '62\n', '75\n', '90']
lis_read[-1] = lis_read[-1]+"\n"

lis_all = lis_input + lis_read
lis_all.sort()
#['10\n', '35\n', '59\n', '60\n', '62\n', '75\n', '85\n', '90\n']
lis_all[-1] = lis_all[-1].strip("\n")
strr_all = "".join(lis_all)
#'10\n35\n59\n60\n62\n75\n85\n90'

print(strr_all)

with open("write.txt","w") as f:
    f.write(strr_all)

輸出結果:

Python TQC考題706: 整數檔案讀寫;使用str type 排序會出現什麼問題? - 儲蓄保險王

輸出的結果看起來是正確的
但評測為答案錯誤!

推薦hahow線上學習python: https://igrape.net/30afN

input的數字全部都兩位數
使用str type排序也看不出錯誤
若是有三位數的數字
會出現以下情況:

Python TQC考題706: 整數檔案讀寫;使用str type 排序會出現什麼問題? - 儲蓄保險王

110排序在20之前,
因為1 < 2
可能有用不同的input去評測
改用int type排序
code:

# -*- coding: utf-8 -*-
"""
Created on Mon Nov 20 21:34:48 2023

@author: SavingKing

"""
lis_input=[]
for i in range(4):
    lis_input.append(input())
#['10', '35', '60', '85']

lis_input = [int(strr.strip("\n")) for strr in lis_input]

with open("read.txt","r") as f:
    lis_read = f.readlines()
#['59\n', '62\n', '75\n', '90']
# lis_read[-1] = lis_read[-1]+"\n"
lis_read_int = [ int(strr.strip("\n")) for strr in lis_read ]

lis_all_int = lis_input + lis_read_int
lis_all_int.sort()
#[10, 35, 59, 60, 62, 75, 85, 90]
lis_all = [str(num)+"\n" for num in lis_all_int ]
#['10\n', '35\n', '59\n', '60\n', '62\n', '75\n', '85\n', '90\n']
lis_all[-1] = lis_all[-1].strip("\n")
strr_all = "".join(lis_all)
#'10\n35\n59\n60\n62\n75\n85\n90'

print(strr_all)

with open("write.txt","w") as f:
    f.write(strr_all)

輸出結果:

Python TQC考題706: 整數檔案讀寫;使用str type 排序會出現什麼問題? - 儲蓄保險王

需要input三位數的數字
才看得出來coding是否有誤
評測後:答案正確

推薦hahow線上學習python: https://igrape.net/30afN

加入好友
加入社群
Python TQC考題706: 整數檔案讀寫;使用str type 排序會出現什麼問題? - 儲蓄保險王

儲蓄保險王

儲蓄險是板主最喜愛的儲蓄工具,最喜愛的投資理財工具則是ETF,最喜愛的省錢工具則是信用卡

You may also like...

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *