-2

So I want to create functions for the median, mean and mode of a list. The list must be a user input. How would I go about this? Thanks.

Nanor
  • 79
  • 2
  • 7
  • What have you tried so far and what was the problem with it? – mkrieger1 Mar 27 '19 at 18:16
  • 1
    It is important to try to search for answers before posting a questions. This problem can be broken down into 4 questions: 1) How can I get a list of number from a user input? 2) How can I get the mean of a list? 3)...How can I get the median of a list? And this depends on if you can use libraries or not, which @Bence Kővári did a good job of explaining, and provided answers to how you might solve the thing if you can't use libraries. Answers to the simpler questions are on stack overflow already. E.g. Q1 https://stackoverflow.com/questions/4663306/get-a-list-of-numbers-as-input-from-the-user – bart cubrich Mar 27 '19 at 19:06

1 Answers1

1

You do not have to create functions for median, mean, mode because they are implemented already and can be called explicitly using Numpy and Scipy libraries in Python. Implementing these functions would mean "reinventing the wheel" and could lead to errors and take time. Feel free to use libraries because in most cases they are tested and safe to use. For example:

import numpy as np
from scipy import stats

mylist = [0,1,2,3,3,4,5,6]
median = np.median(mylist)
mean = np.mean(mylist)
mode = int(stats.mode(mylist)[0])

To get user input you should use input(). See https://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/io.html

If this supposed to be your homework, I'll give you some hint:

mean: iterate through the list, calculate the sum of elements and divide by element count

median: First, you have to sort the list elements in increasing order. Then find out whether the list length is even or odd. If odd, return the center element. If even, return center element and the element next to the the center and calculate their average.

mode: Create a 'helper' list first containing distinct elements of the input list. Then, create a function that has one parameter: a number to - to be counted - how many times it is in the input list. Run this function in a for cycle providing the distinct list elements as input. At each iteration, save the result in a tuple: a tuple consists of (element value, element count). Afterall you should have an array of tuples. When you have all this stuff, select the tuple that has the maximum "element count" and return the corresponding "element value".

Please note that these are just fast hints that can be useful in order to create your own implementation based on the right algorithm you prefer. This could be a good exercise to get started with algorithms and data structures, I hope you'll not skip it:) Good luck!

Bence Kővári
  • 153
  • 1
  • 8