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

User Keysl
by
4.8k points

1 Answer

4 votes

Answer:

  1. def median(l):
  2. if(len(l) == 0):
  3. return 0
  4. else:
  5. l.sort()
  6. if(len(l)%2 == 0):
  7. index = int(len(l)/2)
  8. mid = (l[index-1] + l[index]) / 2
  9. else:
  10. mid = l[len(l)//2]
  11. return mid
  12. def mode(l):
  13. if(len(l)==0):
  14. return 0
  15. mode = max(set(l), key=l.count)
  16. return mode
  17. def mean(l):
  18. if(len(l)==0):
  19. return 0
  20. sum = 0
  21. for x in l:
  22. sum += x
  23. mean = sum / len(l)
  24. return mean
  25. lst = [5, 7, 10, 11, 12, 12, 13, 15, 25, 30, 45, 61]
  26. print(mean(lst))
  27. print(median(lst))
  28. print(mode(lst))

Step-by-step explanation:

Firstly, we create a median function (Line 1). This function will check if the the length of list is zero and also if it is an even number. If the length is zero (empty list), it return zero (Line 2-3). If it is an even number, it will calculate the median by summing up two middle index values and divide them by two (Line 6-8). Or if the length is an odd, it will simply take the middle index value and return it as output (Line 9-10).

In mode function, after checking the length of list, we use the max function to estimate the maximum count of the item in list (Line 17) and use it as mode.

In mean function, after checking the length of list, we create a sum variable and then use a loop to add the item of list to sum (Line 23-25). After the loop, divide sum by the length of list to get the mean (Line 26).

In the main program, we test the three functions using a sample list and we shall get

20.5

12.5

12

User Tanmaya Meher
by
4.6k points