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]))
def stats_finder(array): mean = sum(array)/len(array) count = [[],[]] for item in array: numbers = count[0] if item not in numbers: count[0].append(item) count[1].append(1) else: pos = count[0].index(item) count[1][pos] += 1 mode = 0 max_rep = 0 repetitions = count[1] for index, rep in enumerate(repetitions): if rep > max_rep: max_rep = rep mode = count[0][index] elif rep == max_rep: mode = min(count[0][index], mode) return [mean, mode] print(stats_finder([500, 400, 400, 375, 300, 350, 325, 300]))

Hello,

I’ve added my code below, it completes the breif although it’s a bit lengthier than I would of liked. Does anyone have any suggestions on how this could of been streamlined a bit?

def stats_finder(array): # Write your code here output_list = [] #calculate mean def calculate_mean(array): mean = 0 total = 0 for n in array: total += n mean = total / len(array) output_list.append(mean) #calculate mode def calculate_mode(array): holder = 0 highest_vol = 0 for n in array: vol = array.count(n) if holder == 0: holder = n highest_vol = vol if vol > highest_vol: holder = n highest_vol = vol if vol == highest_vol and n < holder: holder = n highest_vol = vol output_list.append(holder) #call nested functions calculate_mean(array) calculate_mode(array) return output_list print(stats_finder([500, 400, 400, 375, 300, 350, 325, 300])) print(stats_finder([1, 2, 4, 5, 5, 7, 7, 8]))

Many Thanks

My solution for the mean/mode Python Coding Challenge

Calculate the Mean and Mode

Create a stats_finder() function that takes in a list of numbers and returns a list containing the mean and mode, in that order. As a reminder, the mean is the average of the values and the mode is the most occurring value. If there are multiple modes, return the mode with the lowest value. Make sure that you write your functions and find these answers from scratch – don’t use imported tools!

For example, stats_finder([500, 400, 400, 375, 300, 350, 325, 300]) should return [368.75, 300].

def stats_finder(array): # Write your code here mean = sum(array) / len(array) #print(mean) confirming result dup = [] mean_mode = [] mean_mode.append(mean) for num in range(0, len(array)): for n in range(num + 1, len(array)): if array[num] == array[n]: dup.append(array[n]) mode = min(dup) mean_mode.append(mode) return mean_mode print(stats_finder([20, 30, 20, 50, 30, 100, 100, 90, 10])) print(stats_finder([500, 400, 400, 375, 300, 350, 325, 300]))
def stats_finder(a): a.sort(reverse=True) mm, c = [], 1 mode = [a[0],1] mm.append( sum(a) / len(a) ) for x in range(1,len(a)): if a[x-1] == a[x]: c+=1 else: c=1 if c >= mode[1]: mode[0], mode[1] = a[x], c mm.append(mode[0]) return mm print(stats_finder([500, 400, 400, 375, 300, 350, 325, 300]))

sort it, then only call the one at index 0

My code below. I really like some of the other posted solutions for finding the smallest mode. Certainly min() would be easier than sorting and indexing.

def stats_finder(array): Average = (sum(array)/ len(array)) frequency = {} #frequency dict for Mode for value in array: frequency[value] = frequency.get(value, 0) + 1 most_frequent = max(frequency.values()) Mode = [key for key, value in frequency.items() if value == most_frequent] Mode.sort() #ordering to ensure I take smallest return [Average, Mode[0]] #Always take smallest number print(stats_finder([500, 400, 400, 375, 300, 350, 325, 300]))

Sorry, I’ve forgotten which mode to return, the first? or the last?

The first. You could also use the min() function as well.

1 Like

This is what I could come up with, is there a more efficient way to do the mode? Any feedback on readability would also be amazing

type or paste code def stats_finder(array):
    #sum part     
    s = 0
    length = 0
    mode_dict = {}
    for i in array:
        s += i
        length += 1
        if i not in mode_dict:
          mode_dict[i] = 1
        else:
          mode_dict[i] += 1
    mean = s/length

    # mode part    
    max_count = 0
    most_values = list()
    for key, value in mode_dict.items():  
        if value > max_count:
            most_values = []
            max_count = value
            most_values.append((key,value))
        elif value == max_count:
            most_values.append((key,value))
    
    mode = None
    for (key, value) in most_values:
        if mode is None:
            mode = key
        elif mode > key:
            mode = key

    return [mean, mode]

print(stats_finder([500, 400, 400, 375, 300, 350, 325, 300]))
def stats_finder(array):
  # Write your code here
  length_lists = len(array)
  i = 0
  y = []
  mode_container = []
  total = 0
  mean = 0

  while i < length_lists:
    for num in array:
      x = array.count(num)
      total += array[i]
      i += 1
      y.append(x)
  mode_occ = max(y)
  mean = total/length_lists
  
  for num_max in array:
    if array.count(num_max) == mode_occ:
      if num_max not in mode_container:
        mode_container.append(num_max)
  if len(mode_container) > 1:
    mode = min(mode_container)
  else:
    mode = mode_container
    
  return [mean, mode]

print(stats_finder([500, 400, 400, 375, 300, 350, 325, 300]))

Here’s my solution for the Mean and Mode challenge, do enlighten me on how to make the script better, also I wonder what are the other test cases though :thinking:

def stats_finder(items):
  meanandmode = []
  meanandmode.append(sum(items)/len(items))
  findmode ={}
  for n in items:
    if n not in findmode:
      findmode[n]= 1
    else:
      findmode[n] += 1
  sorteditems = sorted(findmode.items(),key= lambda x: x[1])
  highest_value = sorteditems[-1][-1]
  H_V_list = [x[0] for x in sorteditems if x[1]== highest_value]
  H_V_list = sorted(H_V_list)
  meanandmode.append(H_V_list[0])
  return meanandmode

here is my not so efficient solution

def stats_finder(array):

Write your code here

total = sum(array)
size = len(array)
mean = total/size

mode = max(set(array), key=array.count)
return[mean, mode]

print(stats_finder([500, 400, 400, 375, 300, 350, 325, 300]))

Can’t remember, are we supposed to return the first mode or the second one?

I think it says the mode with the lowest value.

1 Like

from numpy import mean
from scipy import stats

stats_finder = lambda i: [mean(i), stats.mode(i)[0][0]]

print(stats_finder([500, 400, 400, 375, 300, 350, 325, 300]))