Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the range of data from a list in Python

I have a set of data that is in a list. I am not sure how to make a function which can take the range of that data and return the min and max values in a tuple.

data:

[1,3,4,463,2,3,6,8,9,4,254,6,72]

my code at the moment:

def getrange(data):
    result=[]
    if i,c in data:
        range1 = min(data)
        range2 = max(data)
        result.append(range1, range2)
    return result 
like image 513
Ninja Avatar asked Nov 30 '22 17:11

Ninja


2 Answers

This is a very straight forward question and you're very close. If what I have below isn't correct, then please edit your question to reflect what you would like.

Try this.

def minmax(val_list):
    min_val = min(val_list)
    max_val = max(val_list)

    return (min_val, max_val)

Semantics

I have a set of data that is in a list.

Be careful here, you're using python terms in a contradictory manner. In python, there are both sets and lists. I could tell you meant list here but you could confuse people in the future. Remember, in python sets, tuples, and lists are all different from one another.

Here are the differences (taken from BlackJack's comment below)

Data Type | Immutable | Ordered | Unique Values
===============================================
  lists   |    no     |   yes   |      no
  tuples  |    yes    |   yes   |      no
   sets   |    no     |   no    |      yes

Immutable - the data type can't be changed after instantiation.

Ordered - the order of the elements within the data type are persistent.

Unique Values - the data type cannot have repeated values.

like image 170
Austin A Avatar answered Dec 05 '22 11:12

Austin A


If You Are Looking To Get The Range Of The Numbers, You Can Use:

def getrange(numbers):
    return max(numbers) - min(numbers)

I've Also Constructed This Code That You Can Use In Finding Averages:

def average(numbers, type=None):
import statistics
try:
    statistics.mean(numbers)
except:
    raise RuntimeError('An Error Has Occured: List Not Specified (0018)')
if type == 'mean':
    return statistics.mean(numbers)
elif type == 'mode':
    return statistics.mode(numbers)
elif type == 'median':
    return statistics.median(numbers)
elif type == 'min':
    return min(numbers)
elif type == 'max':
    return max(numbers)
elif type == 'range':
    return max(numbers) - min(numbers)
elif type == None:
    return average(numbers, 'mean')
else:
    raise RuntimeError('An Error Has Occured: You Entered An Invalid Operation (0003)')

All You Need To Do Is Type average([1, 2, 3]) To Get The Mean Average For 1, 2 And 3. For Other Commands, Do average([1, 2, 3, 'median') And This Will Give The Median Of The Numbers. You Can Change median to: mean, mode, median, min, max and range

like image 38
Richie Bendall Avatar answered Dec 05 '22 13:12

Richie Bendall