Как найти последний минимальный элемент массива питон

>>> values = [1,2,3,4,1,2]
>>> -min((x, -i) for i, x in enumerate(values))[1]
4

No modification to the original list, works for arbitrary iterables, and only requires one pass.

This creates an iterable of tuples with the first value being the original element from the list, and the second element being the negated index. When finding the minimum in this iterable of tuples the values will be compared first and then the indices, so you will end up with a tuple of (min_value, lowest_negative_index). By taking the second element from this tuple and negating it again, you get the highest index of the minimum value.

Here is an alternative version that is very similar, but uses a key function for min():

>>> min(range(len(values)), key=lambda i: (values[i], -i))
4

Note that this version will only work for sequences (lists, tuples, strings etc.).

vuktory1945

1 / 1 / 0

Регистрация: 13.01.2020

Сообщений: 43

1

Найти последний минимальный элемент

27.05.2020, 15:21. Показов 2117. Ответов 3

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Найти номера первого максимального и последнего минимального элементов
Не знаю как сделать, чтоб программа выводила номер последнего минимального элемента, если есть совпадающие элементы
Пример
Входные данные:
7
1 5 8 2 1 5 7
Выходные данные
3 5

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
N=int(input())
a=list(map(int,input().split()[:N]))
max=a[0]
min=a[0]
i_max=0
i_min=0
for i in range(N):
    if a[i]>max:
        max=a[i]
        i_max=i
for i in range(N):
    if a[i]<min:
        min=a[i]
        i_min=i
print(i_max+1,i_min+1)



0



Заклинатель змей

611 / 508 / 213

Регистрация: 30.04.2016

Сообщений: 2,412

27.05.2020, 15:50

2

vuktory1945, min, max — встроенные в питон названия функций, не стоит так назвать переменные



1



Fudthhh

Модератор

Эксперт Python

2869 / 1572 / 508

Регистрация: 21.02.2017

Сообщений: 4,197

Записей в блоге: 1

27.05.2020, 15:53

3

Python
1
2
3
4
5
n = 7
elements = [1, 5, 8, 2, 1, 5, 7]
 
print(elements.index(max(elements)) + 1,
    n - elements[::-1].index(min(elements)))



1



Вадим Тукаев

305 / 286 / 116

Регистрация: 23.01.2018

Сообщений: 933

27.05.2020, 21:32

4

Python
1
2
3
4
5
6
7
8
9
input()
a = list(map(int, input().split()))
b, c = 0, 0
for i in range(1, len(a)):
    if a[i] > a[b]:
        b = i
    elif a[i] <= a[c]:
        c = i
print(b + 1, c + 1)



1



Нужно найти минимальный элемент массива, введенного с консоли, при этом не используя функцию min

massiv = []
dlina = int(input())
for y in range(0, dlina):
    massiv.append(int(input()))
for i in range(0, len(massiv)):
    min = massiv[0]
    if massiv[i] <= min:
        min = massiv[i]
print(min)

Не могу понять, почему выводит правильный ответ через раз.

задан 16 ноя 2021 в 22:01

leyflow's user avatar

1

Причина в том, что вы каждую итерацию цикла перезаписываете min нулевым элементом массива. Строку min = massiv[0] нужно вынести до цикла, вот так:

massiv = []
dlina = int(input())
for y in range(0, dlina):
    massiv.append(int(input()))
min = massiv[0]
for i in range(0, len(massiv)):
    if massiv[i] <= min:
        min = massiv[i]
print(min)

ответ дан 16 ноя 2021 в 22:06

Dafter's user avatar

DafterDafter

5632 серебряных знака16 бронзовых знаков

Вы постоянно устанавливаете минимум в цикле, что неправильно

Так же я бы заменил цикл

massiv = []
dlina = int(input())
for y in range(0, dlina):
    massiv.append(int(input()))
min_value = massiv[0]
for number in massiv:
    if number < min_value:
        min_value = number
print(min_value)

ответ дан 16 ноя 2021 в 22:06

Andrey Maslov's user avatar

Andrey MaslovAndrey Maslov

2,9601 золотой знак5 серебряных знаков11 бронзовых знаков

во первых не очень хорошо использовать в качестве названия переменной название существующей функции

а ошибка в том, что присваивание минимального значения происходит внутри цикла, вынесите ее наружу цикла и все будет хорошо

кроме того зачем использовать <= при сравнении с минимальным значением, когда достаточно строгого меньше

ну и код поджать можно вот так еще:

data = [int(input()) for y in range(0, int(input()))]

value_min = data[0]
for value in data:
    value_min = value if value_min > value else value_min

print(value_min)

ответ дан 16 ноя 2021 в 22:16

Zhihar's user avatar

ZhiharZhihar

36.9k4 золотых знака25 серебряных знаков67 бронзовых знаков

Я бы на вашем месте отсортировал бы список и по индексу доставал значение

пример кода

massiv = []
dlina = int(input())
for y in range(0, dlina):
    massiv.append(int(input()))

massiv.sort()

print(massiv[0])

ответ дан 16 ноя 2021 в 22:16

Andromeda's user avatar

3

  1. Use the min() and index() Functions to Find the Index of the Minimum Element in a List in Python
  2. Use the min() Function and for Loop to Find the Index of the Minimum Element in a List in Python
  3. Use the min() and enumerate() Functions to Find the Index of the Minimum Element in a List in Python
  4. Use the min() and operator.itemgetter() Functions to Find the Index of the Minimum Element in a List in Python
  5. Use the min() and __getitem__() Functions to Find the Index of the Minimum Element in a List in Python
  6. Use the numpy.argmin() Function to Find the Index of the Minimum Element in a List in Python
  7. Conclusion

Find Index of Minimum Element in a List in Python

A list object in Python emulates an array and stores different elements under a common name. Elements are stored at a particular index which we can use to access them.

We can perform different operations with a list. It is straightforward to use built-in list functions like max(), min(), len, and more to return the maximum element, smallest element, and list length.

This article will find the minimum element index in a Python list.

Use the min() and index() Functions to Find the Index of the Minimum Element in a List in Python

In Python, we can use the min() function to find the smallest item in the iterable. Then, the index() function of the list can return the index of any given element in the list.

A ValueError is raised if the given element is not in the list.

Example:

lst = [8,6,9,-1,2,0]
m = min(lst)
print(lst.index(m))

Output:

Remember, the index of a list starts from 0. The above answer shows 3 since the smallest element is in the fourth position.

Use the min() Function and for Loop to Find the Index of the Minimum Element in a List in Python

We can substitute the use of the index() function in the previous method with a for loop. It can iterate over the list and compare elements individually.

When there is a match, we return the value of that index and break out of the loop using the break statement.

Example:

lst = [8,6,9,-1,2,0]
m = min(lst)
for i in range(len(lst)):
    if(lst[i]==m):
        print(i)
        break

Output:

Use the min() and enumerate() Functions to Find the Index of the Minimum Element in a List in Python

The enumerate() function accepts an iterable. It returns an object containing the elements of the iterable with a counter variable for the element index.

This object can be iterated using a for loop. Then, we will iterate over this object using list comprehension, create a new list, and use the min() function to locate the minimum element in a list.

We will get the element and its index in one line.

Example:

lst = [8,6,9,-1,2,0]
a,i = min((a,i) for (i,a) in enumerate(lst))
print(i)

Output:

Use the min() and operator.itemgetter() Functions to Find the Index of the Minimum Element in a List in Python

The operator module in Python provides additional operators which we can use to simplify our code. The itemgetter() function from this module returns a callable object and can retrieve some element from its operand.

The min() function accepts a key parameter to determine the criteria for the comparison. We can provide the itemgetter() function as the value for this parameter to return the index of the minimum element.

Example:

from operator import itemgetter
lst = [8,6,9,-1,2,0]
i = min(enumerate(lst), key=itemgetter(1))[0]
print(i)

Output:

We first find the minimum element and its index in the previous methods. This method does both these steps in one line; therefore, it is considered a faster approach.

Use the min() and __getitem__() Functions to Find the Index of the Minimum Element in a List in Python

The operator.itemgetter() function calls the magic function __getitem__() internally. We can avoid the need for importing the operator module by directly working with this function and improving the speed of the code.

It is similar to the previous method to return the minimum element index in a list in Python.

Example:

lst = [8,6,9,-1,2,0]
i = min(range(len(lst)), key=lst.__getitem__)
print(i)

Output:

Use the numpy.argmin() Function to Find the Index of the Minimum Element in a List in Python

The numpy.argmin() function is used to find the position of the smallest element in Python. We can use this function with lists, and it will return an array with the indices of the minimum element of the list.

Example:

import numpy as np
lst = [8,6,9,-1,2,0]
i = np.argmin(lst)
print(i)

Output:

Conclusion

To wrap up, we discussed several methods to find the index of the minimum element in a list. The min() function was the most common among all the methods.

Different functions like enumerate(), itemgetter(), and more can be used to create different approaches. The final method, using the numpy.argmin() function, is more straightforward.

In this tutorial, we will look at how to find the min value in a Python list and its corresponding index with the help of some examples.

How to get the minimum value in a list in Python?

A simple approach is to iterate through the list and keep track of the minimum value. Alternatively, you can also use the Python built-in min() function to find the minimum value in a list.

minimum value in a list

Let’s look at some of the different ways of finding the smallest value and its index in a list.

Loop through the list to find the minimum

Iterate through the list values and keep track of the min value. Here’s an example.

# create a list
ls = [3, 6, 7, 2, 1, 5]

# find min value using loop
min_val = ls[0]
for val in ls:
    if val < min_val:
        min_val = val
# display the min value
print(min_val)

Output:

1

Here, we iterate over each value in the list ls and keep track of the minimum value encountered in the variable min_val. After the loop finishes, the variable min_val stores the minimum value present in the list, 1.

You can use this method to get the index corresponding to the minimum value in the list as well. Use an additional variable to keep track of the current minimum value’s index.

# create a list
ls = [3, 6, 7, 2, 1, 5]

# find min value using loop
min_val = ls[0]
min_val_idx = 0
for i in range(len(ls)):
    if ls[i] < min_val:
        min_val = ls[i]
        min_val_idx = i
    
# display the min value
print(min_val)
# display its index
print(min_val_idx)

Output:

1
4

We get the minimum value and its index after the loop finishes. Here we iterate through the list via its index rather than the values. You can also use the enumerate() function to iterate through the index and value together.

Using min() to get the maximum value

You can also use the Python built-in min() function to get the min value in a list. The function returns the minimum value in the passed iterable (for example, list, tuple, etc.).

# create a list
ls = [3, 6, 7, 2, 1, 5]
# find min value
min(ls)

Output:

1

Using the min() function is simple and is just a single line code compared to the previous example.

You can use the list index() function to find the index corresponding to the minimum value (assuming you already know the minimum value).

# create a list
ls = [3, 6, 7, 2, 1, 5]

# find min value
min_val = min(ls)
# display the min value
print(min_val)
# display its index
print(ls.index(min_val))

Output:

1
4

We get the min value and its index in the list ls.

Note that the list index() function returns the index of the first occurrence of the passed value. If the min value occurs more than once in the list, you’ll only get the index of its first occurrence. You can use list comprehension to get all the indices of occurrence of the min value in the list.

# create a list
ls = [3, 6, 1, 2, 1, 5]

# find min value
min_val = min(ls)
print(min_val)
# find all indices corresponding to min val
min_val_idx = [i for i in range(len(ls)) if ls[i]==min_val]
print(min_val_idx)

Output:

1
[2, 4]

We get all the indices where the minimum value occurs in the list ls.

You might also be interested in –

  • Find Mode of List in Python
  • Python – Get median of a List

Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.

  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

    View all posts

Понравилась статья? Поделить с друзьями:
  • Геншин импакт как найти недостающие анемокулы
  • Как найти мужа главная героиня
  • Как найти быстро книгу в библиотеке
  • Как найти сколько дней в году
  • Ошибка 0х00000001а windows 7 как исправить