Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: I'm trying to find the maximum difference between two elements in a list

Tags:

python

I need to find the maximum difference in a list between any two elements. In list [1,2,3,4,5] the maximum difference is 4 (between elements 1 and 5) using for loops.

This program needs to output the location of these two elements (0 and 4) and their values (1 and 5).

I can only figure out how to find the max difference between consecutive values, but this creates a problem if the maximum starts elsewhere, e.g. [4,1,6,3,10,8] where the largest difference is between 1 and 10 (positions 1 and 4). Can someone help me?

like image 859
user3452835 Avatar asked Mar 23 '14 17:03

user3452835


1 Answers

You can use the built-in functions max and min to find the maximum and minimum values respectively and then use the list method index to find their indices in the list.

numlist = [1, 2, 3, 4, 5]

max_val = max(numlist)
min_val = min(numlist)

max_pos = numlist.index(max_val)
min_pos = numlist.index(min_val)
like image 101
ajay Avatar answered Sep 21 '22 07:09

ajay