Python计算学生统计数据

时间:2016-02-22 01:59:51

标签: python

我正在尝试使用Python计算学生统计数据。除了最后的标准偏差部分外,一切似乎都运行良好。我以为我正确地解释了公式,但显然不是。我一直得到6.63而不是实际的7.48。帮助将受到高度赞赏。更新:我做了数学。当我的代码生成Summation = 220时,总和实际上应该是279.也许这会帮助你们中的一些人,包括我,尝试找到问题。

nums=[]
total= 0
count= 0

x = int(input("Enter a number (enter -1 to terminate): "))
while x >= 0:
    if x <= 100:
        total = total + x
        count+=1
        nums.append(x)
    if x>100:
            print("Invalid entry.")
    x = int(input("Enter a number (enter -1 to terminate): "))


print(nums)
print("Number of scores: ", count)      

idx=0
while idx < count:
    newIndex = idx+1
    maximum = nums[idx]
    while newIndex < count:
        if(nums[newIndex] < maximum):
            maximum = nums[newIndex]
        newIndex+=1

    if maximum < nums[idx]:
        temp = nums[idx]
        nums[idx] = maximum
        nums[newIndex-1] = temp
    idx+=1
print("Maximum score: ", maximum)

idx= 0
while idx< count:
    newIndex= idx+1
    minimum= nums[idx]
    while newIndex < count:
        if (nums[newIndex]> minimum):
            minimum= nums[newIndex]
        newIndex+=1
    if minimum> nums[idx]:
        temp= nums[idx]
        nums[idx]= minimum
        nums[newIndex-1]= temp
    idx+=1
print("Minimum score: ", minimum)
average=total/count
print ("Average score: ", average)

summation=0
idx=0
while idx< count:
    value= nums[idx]
    if idx<count:
        summation += ((value-average)**2)
    idx+=1
print("Standard Deviation: ", int(summation/count)**0.5)

2 个答案:

答案 0 :(得分:1)

尝试将代码更改为:

(float(summation)/count)**0.5)

答案 1 :(得分:1)

你错了

    if(nums[newIndex] < maximum):
        maximum = nums[newIndex]

比较应为>而不是<

编辑

if maximum < nums[idx]:
    temp = nums[idx]
    nums[idx] = maximum
    nums[newIndex-1] = temp

为您的nums添加... ...如果您设置nums = [50, 40, 30, 20, 10]并完成第一个while idx < count:循环,则会返回nums = [10, 20, 20, 20, 30]查找最大值不应更改基础数据! (为什么你在循环中有一个循环来找到最大值?它只需要一次通过!)

事实上,您可以在一次通过中找到最大值和最小值,如下所示:

maximum = minimum = nums[0]  # initialize to the first value
idx = 1                      # start comparisons against the second value
while idx < count:
    if maximum < nums[idx]:
        maximum = nums[idx]
    if minimum > nums[idx]:
        minimum = nums[idx]
    idx += 1
print("Maximum score: ", maximum)
print("Minimum score: ", minimum)