gpt4 book ai didi

Python 练习 : Calculates the minimum and maximum score for each student.

转载 作者:太空宇宙 更新时间:2023-11-03 14:08:31 25 4
gpt4 key购买 nike

这里是编程的新手,需要您的指导。

我正在通过一些免费的在线类(class)学习 Python,然后遇到这个我已经解决的特定练习,但令我困惑的是有两种不同的方法会产生不同的结果。所以就这样..

问题:使用文本文件 studentdata.txt(如下所示)编写一个程序来计算每个学生的最低和最高分数。也打印出他们的名字。

studentdata.txt:
joe 10 15 20 30 40
bill 23 16 19 22
sue 8 22 17 14 32 17 24 21 2 9 11 17
grace 12 28 21 45 26 10
john 14 32 25 16 89

我最后的尝试:

xFile = open("studentdata.txt", "r")

for xLine in xFile:
xList = xLine.split()
min = 100
max = 0

for x in xList[1:]:
if int(x) > max:
max = int(x)
for x in xList[1:]:
if int(x) < min:
min = int(x)

print(xList[0],"\tmin: ",min,"\tmax: ",max)

xFile.close()

结果:

joe min: 10 max: 40
bill min: 16 max: 23
sue min: 2 max: 32
grace min: 10 max: 45
john min: 14 max: 89

然后我将它与网站提供的给定答案进行了比较(我以我的风格重写了它):

xFile = open("studentdata.txt", "r")

for xLine in xFile:
xList = xLine.split()
print(xList[0],"\tmin: ",min(xList[1:]),"\tmax: ",max(xList[1:]))

xFile.close()

哪个更简单,但产生的结果略有不同(但很重要):

joe min: 10 max: 40
bill min: 16 max: 23
sue min: 11 max: 9
grace min: 10 max: 45
john min: 14 max: 89

请注意,sue 的结果不同。 “自动”版本不会产生正确的结果。这是怎么发生的?

谢谢。

最佳答案

第二个版本的问题在于它在比较之前没有将分数转换为 int。比较字符串时,'32' 出现在 '9' 之前。

您可以通过在使用 minmax 之前将分数转换为 int 来解决此问题:

with open("studentdata.txt", "r") as xFile:
for xLine in xFile:
xList = xLine.split()
scores = [int(x) for x in xList[1:]]
print(xList[0],"\tmin: ",min(scores),"\tmax: ",max(scores))

关于Python 练习 : Calculates the minimum and maximum score for each student.,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41360911/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com