Python Challenge - Calculate the Mean and Mode

Again! I have the right answers but 3/5 tests passed :slight_smile:

def stats_finder(array): # Write your code here stats_array = [] #list with the mean and the mode of our array list sum_stats = 0 #sum of the list's elements if len(array) == 0: return 'You enter an empty list. That is useless. Try with a list full of integers next time' else: #compute the array list's mean for element in array: sum_stats += element #add the mean to our returned list stats_array.append(round(sum_stats / len(array), 2)) #compute the default mode to compare with default_element_mode = array[0] default_count_mode = 0 for element in array: if element == default_element_mode: default_count_mode += 1 #Now we compare our elements with the default ones for element1 in array: new_element_mode = element1 new_count_mode = 0 for element2 in array: if element1 == element2: new_count_mode += 1 #if the new count it's greater than the default count, we select the new mode if new_count_mode > default_count_mode: default_element_mode = new_element_mode #if the new count it's the same as the default and the default mode is greater than the new mode, we select the new mode elif (new_count_mode == default_count_mode) and (default_element_mode > new_element_mode): default_element_mode = new_element_mode #add the mode to our returned list stats_array.append(default_element_mode) return stats_array print(stats_finder([500, 400, 400, 375, 300, 350, 325, 300])) print(stats_finder([])) print(stats_finder([500, 400, 400, 375, 300, 350, 325, 300, 400]))

in [500, 400, 400, 375, 300, 350, 325, 300, 400, 200, 200]
400 appears 3 times
200 appears 2 times
but your code gives the mode as 200.

Take out the rounding stuff earlier.

Also, you need to update the count that you’re comparing new counts against, if you found a higher count,
so

      #if the new count it's greater than the default count, we select the new mode
      if new_count_mode > default_count_mode:
        default_element_mode = new_element_mode

needs to include

        default_count_mode = new_count_mode
1 Like

Thanks @janbazant1107978602 ! I’ll try with those changes

def stats_finder(array): sum = 0 mean_mode = [] indic = 0 for n in array: sum += n count = array.count(n) if count > indic: indic = count index = array.index(n) mode = n elif count == indic and n < array[index]: index = array.index(n) mode = n mean_mode.append(sum / len(array)) mean_mode.append(mode) return mean_mode print(stats_finder([500, 400, 400, 375, 300, 350, 325, 300]))