Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find min, max, and average of a list

Tags:

I am having hard time to figure out how to find min from a list for example

somelist = [1,12,2,53,23,6,17] 

how can I find min and max of this list with defining (def) a function

I do not want to use built-in function min

like image 232
mtkilic Avatar asked Nov 19 '14 04:11

mtkilic


People also ask

How do you find minimum maximum and average?

Keep a minimum variable that is initialized to a high value, and update it if you see a lower value. Do the opposite with a maximum variable. Add up all numbers and divide that sum by the total count to get the average.

How do you find the average of a list?

The average is the sum of all the numbers in a list divided by its length.

How do you find the minimum of a list of numbers?

How to calculate the minimum of a list of numbers? To find the smallest value (the minimum) among a list of numbers, it is necessary to go through the whole list of numbers and compare their values one after the other. The minimum in the list is the smallest value found when all values have been compared.


2 Answers

from __future__ import division  somelist =  [1,12,2,53,23,6,17]  max_value = max(somelist) min_value = min(somelist) avg_value = 0 if len(somelist) == 0 else sum(somelist)/len(somelist) 

If you want to manually find the minimum as a function:

somelist =  [1,12,2,53,23,6,17]   def my_min_function(somelist):     min_value = None     for value in somelist:         if not min_value:             min_value = value         elif value < min_value:             min_value = value     return min_value 

Python 3.4 introduced the statistics package, which provides mean and additional stats:

from statistics import mean, median  somelist =  [1,12,2,53,23,6,17] avg_value = mean(somelist) median_value = median(somelist) 
like image 74
monkut Avatar answered Sep 17 '22 03:09

monkut


Return min and max value in tuple:

def side_values(num_list):     results_list = sorted(num_list)     return results_list[0], results_list[-1]   somelist = side_values([1,12,2,53,23,6,17]) print(somelist) 
like image 39
2RMalinowski Avatar answered Sep 21 '22 03:09

2RMalinowski