这个python源代码有什么问题

时间:2015-07-02 18:22:19

标签: python-3.x error-handling

当我执行此源代码时:1 2 3 4

population = int(input()).split()
def get_deviation(population):
    average = float(sum(population))/float(population)
    s = 0
    for n in population:
        s += float((n-average)**2)

    deviation = float(s**0.5)    
    print(deviation)

    get_deviation(population)    

我收到此错误:

population = int(input()).split()
ValueError: invalid literal for int() with base 10: '1 2 3'

2 个答案:

答案 0 :(得分:0)

你需要除以len(population);如上所述float(population)是一个列表......

你忘了把你的偏差分开。这应该工作(但更好的仔细检查!)

from math import sqrt

# population = int(input()).split()
population = (1.5, 2.5, 2.5, 2.75, 3.25, 4.75)

def get_deviation(population):
    N = float(len(population))
    average = sum(population)/N
    deviation = sqrt(sum((n-average)**2 for n in population)/N)

    return average, deviation


avg, dev = get_deviation(population)
print(avg, dev)

答案 1 :(得分:0)

average = float(sum(population))/float(population)

此行没有任何意义。您无法按列表划分数字。

尝试

average = float(sum(population))/float(len(population))

希望有所帮助。