python - Calculating weighted average from a list -


this 1 list

[74.0, 96.0, 72.0, 88.0, ['71', '80', '83', '77', '90', '88', '95', '71', '76', '94'], 80.0, 74.0, 98.0, 77.0] 

74 calculated weight .1, 96 weight .1, 72 weight .15, 88 weight .05, average of (71,80,83,77,90,88,95,71,76,94) calculated weight .3, 80 calculated weight .08, 74 weight .08, 98 .09 , lastly 77 .05. each score should multiplied appropriate weight.

here function

def weighted_total_score(student_scores):     return((int(student_scores[0])*.1)+(int(student_scores[1])*.1)+(int(student_scores[2])*.15)+(int(student_scores[3])*.05)+(int(student_scores[4][0])*.3)+(int(student_scores[5])*.08)+(int(student_scores[5])*.08)+(int(student_scores[5])*.09)+(int(student_scores[8])*.05)) 

the expected value should 82.94 getting 78.48

you slicing outer list:

student_scores[4:5][0] 

slicing produces new list, in case 1 element, [0] selects that nested list:

>>> student_scores = [74.0, 96.0, 72.0, 88.0, ['71', '80', '83', '77', '90', '88', '95', '71', '76', '94'], 80.0, 74.0, 98.0, 77.0] >>> student_scores[4:5] [['71', '80', '83', '77', '90', '88', '95', '71', '76', '94']] >>> student_scores[4:5][0] ['71', '80', '83', '77', '90', '88', '95', '71', '76', '94'] 

perhaps want use student_scores[4][0] (no slicing, 4th element) instead? that'd produce '71':

>>> student_scores[4][0] '71' 

you skipping student_scores[5], , indexerror student_scores[9], doesn't exist.

you want avoid typing direct references; specify weights sequence , use zip() generator expression , sum() calculate weighted sum:

def weighted_total_score(student_scores):     weights = .1, .1, .15, .05, .3, .08, .08, .09, .05                      return sum(int(s[0] if isinstance(s, list) else s) * w                s, w in zip(student_scores, weights)) 

this uses isinstance(s, list) detect 1 list object , extract first value that.

if need average of the nested list, calculate on spot:

def average(string_scores):     return sum(map(int, string_scores), 0.0) / len(string_scores)  def weighted_total_score(student_scores):     weights = .1, .1, .15, .05, .3, .08, .08, .09, .05                      return sum(int(average(s[0]) if isinstance(s, list) else s) * w                s, w in zip(student_scores, weights)) 

the average() function here converts each string in list integer, sums integers , divides result length of list. sum() started floating point 0.0 force total float, makes sure division producing float, matters on python 2.


Comments

Popular posts from this blog

PySide and Qt Properties: Connecting signals from Python to QML -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

scala - 'wrong top statement declaration' when using slick in IntelliJ -