使用循环查找python中的最大值和最小值
我有一个任务,让用户输入尽可能多的分数,然后我必须计算最小值和最大值,以及有多少人使用for循环获得这些分数。我计算了平均值和标准偏差: elif user_选项==3:使用循环查找python中的最大值和最小值,python,for-loop,python-3.3,Python,For Loop,Python 3.3,我有一个任务,让用户输入尽可能多的分数,然后我必须计算最小值和最大值,以及有多少人使用for循环获得这些分数。我计算了平均值和标准偏差: elif user_选项==3: total = 0 for val in scores_list: total = total + val average = total/ len(scores_list) print (average) elif user_option == 2: total = 0
total = 0
for val in scores_list:
total = total + val
average = total/ len(scores_list)
print (average)
elif user_option == 2:
total = 0
for val in scores_list:
total = total + val
average = total/ len(scores_list)
diffsquared = 0
sum_diffsquared = 0
for val in scores_list:
diffsquared= (val - average)**2
sum_diffsquared= diffsquared + sum_diffsquared
stdev= sqrt((sum_diffsquared)/len(scores_list))
print(stdev)
有没有办法找到最小值和最大值?类似这样的
min_val = float("inf")
max_val = -float("inf")
count_min = 0
count_max = 0
for val in scores_list:
if val < min_val:
min_val = val
count_min = 1
elif val == min_val:
count_min += 1
if val > max_val:
max_val = val
count_max = 1
elif val == max_val:
count_max += 1
print "Minimum score:", min_val
print "Maximum score:", max_val
print "Number of students with minimum score:", count_min
print "Number of students with maximum score:", count_max
float(“inf”)
东西在Python2.x中也可以工作,但不需要使用此方法。内置函数min()和max()如何:
也不要忘记numpy:
import numpy
scores_array = numpy.array(scores_list)
scores_mean = numpy.mean(scores_array)
scores_std = numpy.std(scores_array)
scores_min = numpy.min(scores_array)
scores_max = numpy.max(scores_array)
需要进行一些重新格式化:/。另外,在pythonIs中,空格比制表符更受欢迎,
if
语句的第一部分是什么?因为您不能从elif
开始…我不能使用内置函数。我必须使用Loop我很确定他不允许使用内置或numpy。啊,好的,对不起。这只是一个学术练习。@GL770谢谢你让我知道。我改为float(“inf”)
和-float(“inf”)
。这应该与Python 3兼容。我认为您的count\u min、count\u max值不正确。想想:分数=[6,6,6,7,7,8,8,9,3,3,2,2,2,1,1]@bcollins是的,这是有原因的,因为在你的代码中,如果找到一个新的最小值,count_min永远不会重置为1。还可以尝试使用该列表运行我的代码。它起作用了。对我来说,它打印:最低分数:1最高分数:9最低分数的学生人数:3最高分数的学生人数:1
在您编辑的列表中,它打印:最低分数:1最高分数:9最低分数的学生人数:2最高分数的学生人数:1
,这是正确的。我认为我的代码在正确性方面没有任何问题。
scores_min = min(scores_list)
scores_max = max(scores_list)
import numpy
scores_array = numpy.array(scores_list)
scores_mean = numpy.mean(scores_array)
scores_std = numpy.std(scores_array)
scores_min = numpy.min(scores_array)
scores_max = numpy.max(scores_array)