164k views
4 votes
Use the Python programming language for this question

A group of statisticians at a local college has asked you to create a set of functions that compute the median and mode of a set of numbers, as defined. Define these functions in a module named stats.py. Also include a function named mean, which computes the average of a set of numbers. Each function should expect a list of numbers as an argument and return a single number. Each function should return 0 if the list is empty. Include the main function that tests the three statistical functions with a given list.

1 Answer

2 votes

Answer:

#definition of "median" function

def median(list):

#checking median condition to make sure the list returns zero if empty

if len(list) == 0:

return 0

#sort the list

list.sort()

#find middle element

mid = len(list) / 2

#check the condition

if len(list) % 2 == 1:

return list[mid]

else:

return (list[mid] + list[mid - 1]) / 2

#definition of "mean" function

def mean(list):

#checking mean condition to make sure the list returns zero if empty

if len(list) == 0:

return 0

#sort the list

list.sort()

#set the value

total = 0

#initiate a for loop

for num in list:

#then we calculate the total

total += num

#return the value

return total/ len(list)

#definition of "mode" function

def mode(list):

#checking mode condition to make sure the list returns zero if empty

if len(list) == 0:

return 0

#declare the variable

num_Dictionary = {}

#check the condition

for digit in list:

num = num_Dictionary.get(digit, None)

if num == None:

num_Dictionary[digit] = 1

else:

num_Dictionary[digit] = num + 1

#getting the maximum value

max_Value = max(num_Dictionary.values())

mode_List = []

for k in num_Dictionary:

if num_Dictionary[k] == max_Value:

mode_List.append(k)

return mode_List

#definition of main function

def main():

#set the list

num_list = [7, 4, 8, 10, 9]

#call the "mean" function with a parameter

print ("Mean of the given list: ", mean(num_list))

#call the "mode" function with a parameter

print ("Mode of the given list:", mode(num_list))

#call the "median" function with a parameter

print ("Median of the given list:", median(num_list))

Step-by-step explanation:

Python 3 was used for the above code.

Each function in the above code is defined starting with the keyword def, the name of the function (mean, median, mode, main) and a pair of parentheses containing the parameter.

The various defined functions in the module are saved as stats.py in the text editor.

User Sameera Lakshitha
by
8.1k points
Welcome to QAmmunity.org, where you can ask questions and receive answers from other members of our community.