Python Challenge - Calculate the Mean and Mode

This community-built FAQ covers the “Calculate the Mean and Mode” code challenge in Python. You can find that challenge here, or pick any challenge you like from our list.

Top Discussions on the Python challenge Calculate the Mean and Mode

There are currently no frequently asked questions or top answers associated with this challenge – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this challenge. Ask a question or post a solution by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this challenge, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!
You can also find further discussion and get answers to your questions over in #get-help.

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head to #get-help and #community:tips-and-resources. If you are wanting feedback or inspiration for a project, check out #project.

Looking for motivation to keep learning? Join our wider discussions in #community

Learn more about how to use this guide.

Found a bug? Report it online, or post in #community:Codecademy-Bug-Reporting

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

So this is the code I cam up with for this one.

not sure if there are less clunky ways of working it out but let me know if there are!

def stats_finder(array):
array.sort(reverse=True)
fin_list =
new_dict = {}
mode_val = 0
mode_key = max(array)
mean_calc = 0
for i in array:
mean_calc += i
if i in new_dict:
new_dict[i] += 1
else:
new_dict[i]=1
for num, mode_count in new_dict.items():
if mode_count >= mode_val:
mode_key = num
mode_val = mode_count
fin_list.append(mean_calc / len(array))
fin_list.append(mode_key)
return fin_list

Write your code here

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

print(stats_finder([-2, 700, 900, -9999, 76.75, 900, 34, 21, 7877, 700, 300, 700, 750, 300, 300, 450, 600, 5, 5, 5]))

def stats_finder(array):
  mean = sum(array) / len(array)
  hist = {}
  for x in array:
    hist[x] = 1 if x not in hist else hist[x] + 1
  y = sorted(hist.items(), key=lambda x: x[1], reverse=True)
  mode = [a for a, b in y if b == y[0][1]][-1]
  return [mean, mode]
  
print(stats_finder([500, 400, 400, 375, 300, 350, 325, 300]))
def stats_finder(array):
  answer = []
  count = 0
  for i in array:
    count+=i
  answer.append(count/len(array))
  answer.append((max(set(array), key = array.count)))
  return answer

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

i do like the other commenter’s way of find the the mean. sum(array)/len(array) is very straightforward!

1 Like

def stats_finder(array):
sum=0
for i in array:
sum+=i

mean=sum/len(array)

mode=0
count=0
count2=0
for i in array:
count=array.count(i)
if count>=count2:
count2=count
mode=i

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

What I don’t understand about this is how do we get at the first/other mode?

def stats_finder(array):
for x in array:
ave = sum(array)/len(array)
freq = max(set(array), key = array.count)
return [ave, freq]

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

def stats_finder(array):
  # Write your code here
  return [sum(array,0)/len(array), max(set(array), key = array.count)]

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

This code feels extremely inefficient. Anyone got any tips on how I can make it better? Thank in advance!

def stats_finder(array):

def FindMean(): #findsmean
counter = 0
mean = 0
for number in array: #every number in the array adds 1 to the counter. The use the counter to find mean
counter += 1
mean += number

new_mean = mean / counter
return(new_mean)

def FindMode():
numbers = {} #create a dictionary where I add the numbers as the key and the value as how often the number has appeared

def CreateDic():
  for num in array: #iterate through the list to add to dictionary: if number is already in dictionary, add 1 to the value

    if num in numbers:
      value = numbers[num]
      value += 1
      numbers[num] = value
  
    else: 
      numbers[num] = 1

  def SortDic(): #sorting the dictionary from high to low (amount of times the numbers have appeared)
    SortedList = sorted(numbers.items(), key = lambda x:x[1], reverse = True)
    SortedDic = dict(SortedList)

    def CompareAmount(): #sees how which number(s) have appeared most often. If a multiple numbers have appeared the same amount of times, it will always compare and keep the smallest number
      first_value = list(SortedDic.items())[0][1]
      NewMode = list(SortedDic.items())[0][0]

      for element in SortedDic:
        if SortedDic[element] == first_value:
          if NewMode > element:
            NewMode = element
          else:
            NewMode = NewMode
        else:
          NewMode = NewMode
      
      return(NewMode)
      

    return CompareAmount()

  return SortDic()

return CreateDic()

return[FindMean(), FindMode()]

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

Edits: added some comments for better readability and understanding my thought process :slight_smile:

Given that an array has a .length property, we could use that without penalty. One would also expect there to be no penalty for using the built in sum() function, which makes the mean rather straight forward. However, as a flat out naive algorithm, you’ve got it right.

The mode can be computed in a number of ways. Take a look up the thread and see if you can correlate yours to any of the other submissions.

1 Like

My code. Definitely feels a bit overcomplicated though…

def stats_finder(array): # Write your code here #Find Mean mean = 0 for val in array: mean += val mean/=len(array) #Find Mode mode = max(array) for val in array: val_count = array.count(val) if val_count > array.count(mode): mode = val elif val_count == array.count(mode) and val < mode: mode = val #Return Stats return[mean, mode] print(stats_finder([500, 400, 400, 375, 300, 350, 325,325,325, 300]))
def stats_finder(array):
  sum=0
  stats=[]
  terms=len(array)
  for number in array:
    sum+=number
  stats.append(sum/terms)
  stats.append(max(set(array), key=array.count))
  return stats

print(stats_finder([500, 400, 400, 375, 300, 350, 325, 300]))
def stats_finder(array): # Write your code here mean = sum(array) / len(array) sarray = sorted(array) counts = {i: sarray.count(i) for i in set(sarray)} keys = list(counts.keys()) values = list(counts.values()) median = keys[values.index(max(values))] return [mean, median]

https://www.codecademy.com/code-challenges/code-challenge-calculate-the-mean-and-mode-python

hello everyone, I’m doing this challenge on codecademy and I’m trying to do this without using any count function and stuff, my code is working on VSC but I’ve just pass 0 test so far, got any tips? this is my code so far.
thank you, #staysafe and #love


def stats_finder(array):
total = 0
mode = 0
d = {}
for number in array:
total += number
mean = total / len(array)
for a in array:
if not a in d:
d[a]=1
else:
d[a]+=1
for k, v in d.items():
if v == max(d.values()):
mode = k
return mean, mode ***

Your code’s fine up to the very last line. Check how it’s expecting the result.

sorted, missing these two beautiful .
Thank you
(what a miss from me)
#staysafe #love

1 Like
def stats_finder(array):
  # Write your code here
  mean = sum(array)/len(array)
  array.sort()
  mode = max(array, key = array.count)
  return [mean,mode]

print(stats_finder([500, 400, 400, 375, 300, 350, 325, 300]))
def stats_finder(array):
  avg = sum(array)/len(array)
  fqs = [array.count(x) for x in array]
  M = dict(zip(array, fqs))
  m = min([key for key in M if M.get(key) == max(fqs)])
  stats = [avg, m]
  return stats
def stats_finder(array): # find mean mean = sum(array) / len(array) # find mode mode = [] not_mode = [] for i in array: if i not in not_mode: not_mode.append(i) else: mode.append(i) mode = min(mode) stats = [mean, mode] return stats print(stats_finder([500, 400, 400, 375, 300, 350, 325, 300]))
1 Like
def stats_finder(array): # Write your code here mean = sum(array)/len(array) counts = {} for num in array: if num in counts.keys(): counts[num] += 1 else: counts.update({num: 1}) sorted_count = [v[0] for v in sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))] mode = sorted_count[0] return [mean, mode] print(stats_finder([500, 400, 400, 375, 300, 350, 325, 300]))