Maximum from list python

Find maximum value and index in a python list?

This list can be up to thousand elements in length, how can I get the maximum value in the list according to the second item in the sub-array, and get the index of the maximum value which is the fist element in the sub-array in python?

You are right @unwind. I think he wants to find all the elements with maximum value according to the second element and find the maximum out of them based on the first value.

well sorry if you guys didn’t get it, it’s like this I want the subarray with the maximum second value, second value means the [1]th item in a subarray

Okay . I still struggle to understand. A small example on e.g. a four or five element list would be helpful. But I guess it’s already solved.

5 Answers 5

Use the max function and its key parameter, to use only the second element to compare elements of the list.

>>> data = [[12587961, 0.7777777777777778], [12587970, 0.5172413793103449], [12587979, 0.3968253968253968]. [12588042, 0.9473684210 526315]] >>> max(data, key=lambda item: item[1]) [12588042, 0.9473684210526315] 

Now, if you want just the first element, then you can simply get the first element alone, or just unpack the result, like this

>>> index, value = max(data, key=lambda item: item[1]) >>> index 12588042 >>> value 0.9473684210526315 

Edit: If you want to find the maximum index (first value) out of all elements with the maximum value (second value), then you can do it like this

>>> _, max_value = max(data, key=lambda item: item[1]) >>> max(index for index, value in data if value == max_value) 

You can do the same in a single iteration, like this

max_index = float("-inf") max_value = float("-inf") for index, value in data: if value > max_value: max_value = value max_index = index elif value == max_value: max_index = max(max_index, index) 

Источник

How can I get the minimum and the maximum element of a list in python

can you tell why you don’t want to use min(l) / max(l) ? because if I were to answer your question here, I’d give you an algorithmic approach pretty close to what min() and max() already does.

8 Answers 8

If you are trying to avoid using two loops, hoping a single loop will be faster, you need to reconsider. Calling two O(N) functions still gives you a O(N) algorithm, all you do is double the constant per-iteration cost. A single Python loop with comparisons can’t do better than O(N) either (unless your data is already sorted), and interpreting bytecode for each iteration has a sizeable constant cost too. Which approach has the higher constant cost can only be determined by timing your runs.

To do this in a single loop, iterate over the list and test each item against the minimum and maximum found so far. float(‘inf’) and float(‘-inf’) (infinity and negative infinity) are good starting points to simplify the logic:

minimum = float('inf') maximum = float('-inf') for item in l: if item < minimum: minimum = item if item >maximum: maximum = item 

Alternatively, start with the first element and only loop over the rest. Turn the list into an iterable first, store the first element as the result-to-date, and then loop over the rest:

iterl = iter(l) minimum = maximum = next(iterl) for item in iterl: if item < minimum: minimum = item if item >maximum: maximum = item 

Don’t use sorting. Python’s Tim Sort implementation is a O(N log N) algorithm, which can be expected to be slower than a straight-up O(N) approach.

Timing comparisons with a larger, random list:

>>> from random import shuffle >>> l = list(range(1000)) >>> shuffle(l) >>> from timeit import timeit >>> def straight_min_max(l): . return min(l), max(l) . >>> def sorted_min_max(l): . s = sorted(l) . return s[0], s[-1] . >>> def looping(l): . l = iter(l) . min = max = next(l) . for i in l: . if i < min: min = i . if i >max: max = i . return min, max . >>> timeit('f(l)', 'from __main__ import straight_min_max as f, l', number=10000) 0.5266690254211426 >>> timeit('f(l)', 'from __main__ import sorted_min_max as f, l', number=10000) 2.162343978881836 >>> timeit('f(l)', 'from __main__ import looping as f, l', number=10000) 1.1799919605255127 

So even for lists of 1000 elements, the min() and max() functions are fastest. Sorting is slowest here. The sorting version can be faster if you allow for in-place sorting, but then you’d need to generate a new random list for each timed run as well.

Moving to a million items (and only 10 tests per timed run), we see:

>>> l = list(range(1000000)) >>> shuffle(l) >>> timeit('f(l)', 'from __main__ import straight_min_max as f, l', number=10) 1.6176080703735352 >>> timeit('f(l)', 'from __main__ import sorted_min_max as f, l', number=10) 6.310506105422974 >>> timeit('f(l)', 'from __main__ import looping as f, l', number=10) 1.7502741813659668 

Last but not least, using a million items and l.sort() instead of sorted() :

>>> def sort_min_max(l): . l.sort() . return l[0], l[-1] . >>> timeit('f(l[:])', 'from __main__ import straight_min_max as f, l', number=10) 1.8858389854431152 >>> timeit('f(l[:])', 'from __main__ import sort_min_max as f, l', number=10) 8.408858060836792 >>> timeit('f(l[:])', 'from __main__ import looping as f, l', number=10) 2.003532886505127 

Note the l[:] ; we give each test run a copy of the list.

Conclusion: even for large lists, you are better off using the min() and max() functions anyway, it is hard to beat the low per-iteration cost of a good C loop. But if you have to forgo those functions, the straight loop is the next better option.

you should have better given him hints instead of giving him the answer, stackoverflow is not for doing assignments for the students! :-s (though your idea of using float’s inf is pretty neat 😉 )

No, Stack Overflow is for answering questions. The OP never asked for hints and we are not here to police homework policies. If I were the professor, I would ask pointed questions about the code in my answer if it was posted as a homework answer to see if the student understands what it does exactly.

In this situation I’d use the iterable = iter(l); minimum = maximum = next(iterable) «pattern». It has the added advantage that it works with every sequence, while l[0] works only with indexed sequences.

ok, as you wish. I won’t troll about this here, as it’s already been done on meta, where it leads to my point. But as you give two different neat ways to implement it, if the OP did not learn something, future readers of the questions will, so forget about my comment. 🙂

print reduce(lambda x,y: x if x>y else y, map(int,raw_input().split())) 
print reduce(lambda x,y: x if x 

Loop through all the elements in the list with the for loop. Set the variable storing the max/min value to the fist element in the list to start with. Otherwise, you could end up with invalid values.

max_v=l[0] for i in l: if i>max_v: max_v=i min_v=l[0] for i in l: if l 

well, as this is an assignment, I won't give you any code, you have to figure it out yourself. But basically, you loop over the list, create two variables iMin and iMax for example, and for each value compare iMin and iMax to that value and assign a new variable iBuf to that one.

Those names seems too java-ish or whatever language uses camelCase + prepending the type, which I believe is totally ugly and misleading in this example(where the function will work with any type that supports comparison).

I'm talking in general algorithm, not specific python, and I used i for meaning index , not integers . I neither like camelCase in python, btw.

Homework questions with weird restrictions demand cheat answers

>>> l = [1,2,3,4,5] >>> sorted(l)[::len(l)-1] [1, 5] 

The fastest approach I can think of would be to sort the original list and then pick the first and last elements. This avoids looping multiple times, but it does destroy the original structure of your list. This can be solved by simply copying the list and sorting only the copied list. I was curious if this was slower than just using max() and min() with this quick example script:

import time l = [1,2,4,5,3] print "Run 1" t1 = time.time() print "Min =", min(l) print "Max =", max(l) print "time =", time.time() - t1 print "" print "l =", l print "" l = [1,2,4,5,3] l1 = list(l) print "Run 2" t1 = time.time() l1.sort() print "Min =", l1[0] print "Max =", l1[-1] print "time =", time.time() - t1 print "" print "l =", l print "l1 =", l1 print "" l = [1,2,4,5,3] print "Run 3" minimum = float('inf') maximum = float('-inf') for item in l: if item < minimum: minimum = item if item >maximum: maximum = item print "Min =", minimum print "Max =", maximum print "time =", time.time() - t1 print "" print "l Min =", min(l) #print "Max =", max(l) return min(l), max(l) def Run_2(): l1 = list(l) l1.sort() #print "Min =", l1[0] #print "Max =", l1[-1] return l1[0], l1[-1] def Run_3(): minimum = float('inf') maximum = float('-inf') for item in l: if item < minimum: minimum = item if item >maximum: maximum = item #print "Min =", minimum #print "Max =", maximum return minimum, maximum if __name__ == '__main__': num_runs = 10000 print "Run 1" run1 = timeit.Timer(Run_1) time_run1 = run1.repeat(3, num_runs) print "" print "Run 2" run2 = timeit.Timer(Run_2) time_run2 = run2.repeat(3,num_runs) print "" print "Run 3" run3 = timeit.Timer(Run_3) time_run3 = run3.repeat(3,num_runs) print "" print "Run 1" for each_time in time_run1: print "time =", each_time print "" print "Run 2" for each_time in time_run2: print "time =", each_time print "" print "Run 3" for each_time in time_run3: print "time =", each_time print "" 
Run 1 time = 3.42100585452 time = 3.39309908229 time = 3.47903182233 Run 2 time = 26.5261287922 time = 26.2023346397 time = 26.7324208568 Run 3 time = 3.29800945144 time = 3.25067545773 time = 3.29783778232 

sort algorithm is very slow for large arrays.

Источник

How to find the maximum number in a list using a loop?

I'm confused about how to actually do it. I want to use this exercise to give me a starter. How do I do that on Python?

11 Answers 11

Usually, you could just use

If you explicitly want to use a loop, try:

max_value = None for n in nums: if max_value is None or n > max_value: max_value = n 

To add some explanation to the loop solution: To get the biggest number, you iterate through the list and remember the biggest number you have encountered so far. That way when you reach the end, you will have the biggest number of them all remembered.

Granted, the name max is ill-chosen. -1 an initial value fails, if all numbers in the list are < -1. I edited the post accordingly.

nums = [14, 8, 9, 16, 3, 11, 5] big = max(nums) spot = nums.index(big) 

This would be the Pythonic way of achieving this. If you want to use a loop, then loop with the current max value and check if each element is larger, and if so, assign to the current max.

@TheodrosZelleke for i in range(len(list)): # for loop iterates through it . That's an explicit way of repeating something for the length of the list. This will work for indices; if you want to do something x amount of times, the range() 'end' argument should be x + 1. So to do something x amount of times where x is the length of the list, do: for i in range(len(list) + 1): .

@F3AR3DLEGEND, thanks for the clarification -- however, my comment was meant as a "kind of criticism" not a question.

@F3AR3DLEGEND list is a builtin function, best not to use it as a variable name. and you're better off doing for i, _ in enumerate(seq) rather than range(len(seq))

nums = [14, 8, 9, 16, 3, 11, 5] big = None spot = None for i, v in enumerate(nums): if big is None or v > big: big = v spot = i 

For bonus points, make sure nums is not empty before assigning big = nums[0] , and if so, raise an exception ( ValueError would be a good choice).

Python already has built in function for this kind of requirement.

list = [3,8,2,9] max_number = max(list) print (max_number) # it will print 9 as big number 

however if you find the max number with the classic vay you can use loops.

list = [3,8,2,9] current_max_number = list[0] for number in list: if number>current_max_number: current_max_number = number print (current_max_number) #it will display 9 as big number 

Why not simply using the built-in max() function:

By the way, some answers to similar questions might be useful:

To address your second question, you can use a for loop:

for i in range(len(list)): # do whatever 

You should note that range() can have 3 arguments: start , end , and step . Start is what number to start with (if not supplied, it is 0); start is inclusive.. End is where to end at (this has to be give); end is exclusive: if you do range(100) , it will give you 0-99. Step is also optional, it means what interval to use. If step is not provided, it will be 1. For example:

>>> x = range(10, 100, 5) # start at 10, end at 101, and use an interval of 5 >>> x [10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95] # note that it does not hit 100 

Since end is exclusive, to include 100, we could do:

>>> x = range(10, 101, 5) # start at 10, end at 101, and use an interval of 5 >>> x [10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100] # note that it does hit 100 

Источник

Читайте также:  Link tags in html with example
Оцените статью