148k views
5 votes
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 in Section 5.4. 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 a main function that tests the three statistical functions. Ask users to enter the list of numbers, and then choose which function to apply to those numbers. After the single number is returned from the correct function, display to the user the list of numbers, the function selected and the answer in a format that is easy to understand.

1 Answer

2 votes

Answer:

from functools import reduce

def mean(mylist):

score = reduce(lambda x,y: x + y, mylist)/ len(mylist)

return score

def median(mylist):

sorted(mylist)

list_len = len(mylist) % 2

i = round(len(mylist)/2)

x = len(mylist)//2

if list_len == 0:

median = (mylist[x] + mylist[x+1]) / 2

else:

median = mylist[i]

return median

def mode(mylist):

unique = set(mylist)

unique = list(unique)

collector = [mylist.count(key) for key in unique]

maxi = max(collector)

loc = collector.index(maxi)

return unique[loc]

def main():

scores = input( 'Enter list of numbers: ').split(",")

scores = [int(score) for score in scores]

operation = input('Enter operation: ')

operator = ['mean', 'median', 'mode']

for x in iter(list, 0):

if operation in operator:

break

print("Invalid operation: ")

operation = input('Enter operation')

index_loc = operator.index(operation)

if index_loc == 0:

return mean(scores)

elif index_loc == 1:

return median(scores)

#return np.median(scores) can be used of the defined function

elif index_loc == 2:

#return stats.mode(scores)[0] can be used of the defined function

return mode(scores)

print( main( ) )

Step-by-step explanation:

The main python function calls conditionally three statistical functions namely mean, median and mode. It prompts for user input for a list of integer numbers and a function name name to return the corresponding result.

User Tudor Vintilescu
by
4.8k points