Hackerrank加权平均数

2024-06-12 02:46:22 发布

您现在位置:Python中文网/ 问答频道 /正文

问题可以找到here

我试图计算加权平均值,但当我试图用for循环填充数组时,它什么都没做?在

size = raw_input()
arr = raw_input()
w = raw_input()
deger = [1,2,2,2,2]


size = [int(i) for i in size.split()]
size = size[0]
arr = [int(i) for i in arr.split()]
w = [float(i) for i in w.split()] 


 def wm (x,y,s):
  for i in range(0,s-1):
    deger[i] = int(input(x[i]*y[i])) 


return sum(deger)



 print(wm(arr,w,size))  

Tags: inforinputsizerawhere数组float
2条回答

只是根据代码的适当缩进进行一些修改:

size = raw_input()
arr = raw_input()
w = raw_input()
#deger = [1,2,2,2,2] # not necessary to initialize 'deger' here


size = [int(i) for i in size.split()]
size = size[0]
arr = [int(i) for i in arr.split()]
w = [float(i) for i in w.split()] 


def wm (x,y,s):
    deger = [] # initialize empty 'deger' here
    for i in range(0,s): # 's-1' will not include the last item of x and y
        deger.append(x[i]*y[i])
    return sum(deger) / sum(y) 

print('%.1f'%wm(arr,w,size)) # as 1 decimal place is required

打印结果之前有一个return

相关问题 更多 >