2016-11-10 115 views
0

的問題可以發現hereHackerrank加權平均

我試圖計算的加權平均,但是當我嘗試填充與循環它只是無所事事的陣列?

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)) 
+3

我希望你的實際代碼不具有靠不住的缺口! 'def'應該在左邊界上並且'return'縮進。無論如何,在計算'x [i] * y [i]'時,不應該使用'int(input(')',你也應該'append()'到'deger',而不是覆蓋以前的值 –

+0

I已經嘗試追加,但我得到**不能分配給函數調用**錯誤 – bukowski

+1

首先閱讀鏈接中提供的教程,因爲你的加權平均值計算不正確 – acw1668

回答

1

正是基於與正確的縮進你的代碼進行一些修改:

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 
1

打印結果之前您有一個return