Как найти индекс минимума в массиве

I need to find the index of more than one minimum values that occur in an array. I am pretty known with np.argmin but it gives me the index of very first minimum value in a array. For example.

a = np.array([1,2,3,4,5,1,6,1])    
print np.argmin(a)

This gives me 0, instead I am expecting, 0,5,7.

Thanks!

Saullo G. P. Castro's user avatar

asked Oct 23, 2013 at 16:09

user2766019's user avatar

2

This should do the trick:

a = np.array([1,2,3,4,5,1,6,1]) 
print np.where(a == a.min())

argmin doesn’t return a list like you expect it to in this case.

answered Oct 23, 2013 at 16:21

Tom Swifty's user avatar

Tom SwiftyTom Swifty

2,8242 gold badges16 silver badges25 bronze badges

2

Maybe

mymin = np.min(a)
min_positions = [i for i, x in enumerate(a) if x == mymin]

It will give [0,5,7].

answered Oct 23, 2013 at 16:20

tonjo's user avatar

tonjotonjo

1,3761 gold badge14 silver badges27 bronze badges

2

I think this would be the easiest way, although it doesn’t use any fancy numpy function

a       = np.array([1,2,3,4,5,1,6,1])                                        
min_val = a.min()                                                            

print "min_val = {0}".format(min_val)                                        

# Find all of them                                                           
min_idxs = [idx for idx, val in enumerate(a) if val == min_val]              
print "min_idxs = {0}".format(min_idxs)

answered Oct 23, 2013 at 16:26

jrk0414's user avatar

jrk0414jrk0414

1441 gold badge1 silver badge11 bronze badges

  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.

Ильгиз95

0 / 0 / 2

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

Сообщений: 69

1

Поиск минимального элемента и его индекса в массиве

09.01.2017, 21:05. Показов 17953. Ответов 6

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


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

всем привет!
не понимаю как искать в массиве тот элемент, который наименьший и вывести этот элемент и с индексом местоположения
точнее каким-образом искать и чем искать???
вот пример

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// massiv.cpp: определяет точку входа для консольного приложения.
//
 
#include "stdafx.h"
#include <iostream>;
using namespace std;
 
 
int _tmain(int argc, _TCHAR* argv[])
{
    int mass[10]= {1,2,3,4,5,6,7,8,9,10};
    int min;
    for(int i=1; i<10; i++)
        cout<<"dan massiv: "<<mass[i]<<endl;
    for (int i = 1; i < 10; i++)
    {min=mass[1];
        if (mass[i]<min)
        {
cout << "min = " << mass[i]<<endl;
        }
    }
    system("pause");
    return 0;
}



0



nd2

3433 / 2812 / 1249

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

Сообщений: 9,426

09.01.2017, 21:08

2

Цитата
Сообщение от Ильгиз95
Посмотреть сообщение

C++
1
for(int i=1; i<10; i++)

Индексация массивов с 0 начинается.



1



STArSka

146 / 27 / 13

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

Сообщений: 62

09.01.2017, 21:12

3

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// massiv.cpp: определяет точку входа для консольного приложения.
//
 
#include "stdafx.h"
#include <iostream>;
using namespace std;
 
 
int _tmain(int argc, _TCHAR* argv[])
{
    int mass[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    int min;
    cout << "dan massiv: " << endl; // не в цикле - так лучше выглядит
    for (int i = 0; i<10; i++) //нумерация от 0
        cout << mass[i] << endl;
    min = mass[0];//пусть первый элемент - минимальный, делаем ВНЕ цикла, чтобы не делать ошибки
    for (int i = 0; i < 10; i++) //нумерация от 0
    {
        if (mass[i]<min)//если есть элемент, меньше нашего - делаем его минимальным
        {
            min = mass[i];
        }
    }
    cout << "min = " << min << endl;//выводим наш минимальный элемент
    system("pause");
    return 0;
}



1



nd2

3433 / 2812 / 1249

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

Сообщений: 9,426

09.01.2017, 21:16

4

Лучший ответ Сообщение было отмечено Ильгиз95 как решение

Решение

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
    int mass[10]= {1,2,3,4,5,6,7,0,9,10};
    
    for(int i=0; i<10; i++)
        cout<<"dan massiv: "<<mass[i]<<endl;
   
    int min = mass[0];
    int ind = 0;
    for (int i = 0; i < 10; i++)
    {
        if (mass[i] < min)
            ind = i;
    }
    cout << "ind = " << ind << endl;
    cout << "min = " << mass[ind] << endl;



1



Ильгиз95

0 / 0 / 2

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

Сообщений: 69

09.01.2017, 21:19

 [ТС]

5

спасибо, маленькие недочеты благодаря вам увидел
как с индексом выводить элемент?

Цитата
Сообщение от STArSka
Посмотреть сообщение

cout <<

C++
1
"min = " << min << endl;//выводим наш минимальный элемент



0



STArSka

146 / 27 / 13

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

Сообщений: 62

09.01.2017, 21:28

6

Простите, я был невнимателен, проглядел необходимость вывода индекса, вот так – работает

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// massiv.cpp: определяет точку входа для консольного приложения.
//
 
#include "stdafx.h"
#include <iostream>;
using namespace std;
 
 
int _tmain(int argc, _TCHAR* argv[])
{
    int mass[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    int min,index;
    cout << "dan massiv: " << endl; // не в цикле - так лучше выглядит
    for (int i = 0; i<10; i++) //нумерация от 0
        cout << mass[i] << endl;
    min = mass[0];//пусть первый элемент - минимальный, делаем ВНЕ цикла, чтобы не делать ошибки
    index = 0;
    for (int i = 0; i < 10; i++) //нумерация от 0
    {
        if (mass[i]<min)//если есть элемент, меньше нашего - делаем его минимальным
        {
            min = mass[i];
            index = i;
        }
    }
    cout << "min = " << min << endl;//выводим наш минимальный элемент
    cout << "index = " << index << endl;
    system("pause");
    return 0;
}



1



0 / 0 / 0

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

Сообщений: 3

18.04.2022, 09:38

7

Спасибо



0



Sometimes, while working with Python lists, we can have a problem in which we intend to find the position of minimum element of list. This task is easy and discussed many times. But sometimes, we can have multiple minimum elements and hence multiple minimum positions. Let’s discuss ways to achieve this task. 

Method #1: Using min() + enumerate() + list comprehension In this method, the combination of above functions is used to perform this particular task. This is performed in two steps. In 1st, we acquire the minimum element and then access the list using list comprehension and corresponding element using enumerate and extract every element position equal to minimum element processed in step 1. 

Python3

test_list = [2, 5, 6, 2, 3, 2]

print("The original list : " + str(test_list))

temp = min(test_list)

res = [i for i, j in enumerate(test_list) if j == temp]

print("The Positions of minimum element : " + str(res))

Output : 

The original list : [2, 5, 6, 2, 3, 2]
The Positions of minimum element : [0, 3, 5]

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #2: Using loop + min() This is brute method to perform this task. In this, we compute the minimum element and then iterate the list to equate to min element and store indices. 

Python3

test_list = [2, 5, 6, 2, 3, 2]

print("The original list : " + str(test_list))

temp = min(test_list)

res = []

for idx in range(0, len(test_list)):

    if temp == test_list[idx]:

        res.append(idx)

print("The Positions of minimum element : " + str(res))

Output : 

The original list : [2, 5, 6, 2, 3, 2]
The Positions of minimum element : [0, 3, 5]

Time Complexity: O(n*n), where n is the length of the input list. This is because we’re using the loop which has a time complexity of O(n) in the worst case.
Auxiliary Space: O(n), as we’re using additional space res other than the input list itself with the same size of input list.

Approach 3: Using numpy

Note: Install numpy module using command “pip install numpy”

The numpy.where() function returns the indices of elements in an array that satisfy a given condition. In this case, the condition is test_list == np.min(test_list), which returns a Boolean array with True at the indices where the elements are equal to the minimum element in the list, and False elsewhere. The [0] at the end is used to extract the indices from the output of numpy.where(), which is a tuple containing the indices in the first element.

Python3

import numpy as np

test_list = [2, 5, 6, 2, 3, 2]

print("The original list : " + str(test_list))

res = np.where(test_list == np.min(test_list))[0]

print("The Positions of minimum element : " + str(res))

Output:

The original list : [2, 5, 6, 2, 3, 2]
The Positions of minimum element : [0 3 5]

Time complexity: O(n)
Auxiliary Space: O(n)

Method 4:  Use a dictionary to store the indices of each unique value in the list. 

Step-by-step approach 

  • Define the input list test_list with some integer values.
  • Print the input list using print().
  • Find the minimum value in the list using the min() function, and store it in the variable min_val.
  • Create an empty dictionary index_dict to store the indices of each unique value in the list.
  • Loop through the elements in test_list using the enumerate() function to get both the index and value at each position in the list.
  • Check if the current value is already in index_dict. If it is not, add a new key-value pair to the dictionary where the key is the value and the value is a list
  • containing the current index. If the value is already in the dictionary, append the current index to the list of indices for that value.
  • Retrieve the list of indices for the minimum value from index_dict and store it in the variable res.
  • Print the list of indices of the minimum element in the original list using print().

Below is the implementation of the above approach:

Python3

test_list = [2, 5, 6, 2, 3, 2]

print("The original list : " + str(test_list))

min_val = min(test_list)

index_dict = {}

for i, x in enumerate(test_list):

    if x not in index_dict:

        index_dict[x] = [i]

    else:

        index_dict[x].append(i)

res = index_dict[min_val]

print("The Positions of minimum element : " + str(res))

Output

The original list : [2, 5, 6, 2, 3, 2]
The Positions of minimum element : [0, 3, 5]

Time complexity: O(n), where n is the length of the list, because it loops through the list once to build the dictionary and once to retrieve the indices of the minimum value. 
Auxiliary space: O(m), where m is the number of unique values in the list, because the dictionary can potentially store indices for each unique value in the list.

Last Updated :
17 Apr, 2023

Like Article

Save Article

 В этой статье рассмотрены два способа нахождения минимального (максимального) элемента массива, а также задачи с применением этих способов.

1 способ

Задача 1: Дан одномерный массив, состоящий из n целых чисел. Найти минимальный элемент массива. В первой строке вводится количество чисел в массиве n. Затем выводятся сами числа, заданные случайным образом. В третьей строке выводится результат: минимальный элемент массива.

Исходные данные:

Результат:

10
5  -2  14  7  -4  23  0  8  6  -1

-4

10
0  4  5  2  77  62  4  8  0  45

0

Считаем, что первый элемент массива – минимальный.  Затем, сравниваем, начиная со второго до последнего все элементы массива с минимальным. Используем для этого цикл. Если очередной элемент на каком-то шаге цикла оказывается меньше минимального, то значение минимального изменяем, присвоив ему значение этого очередного элемента. По окончании цикла выводим результат: минимальный элемент.

program min1;
var a:array[1..100] of integer;
i,min,n:integer;
begin
//заполнение массива и вывод массива в строчку
readln(n);
for i:=1 to n do begin
a[i]:=random(-100,100);
write(a[i],’ ‘);
end;
//нахождение минимального элемента массива
min:=a[1];
for i:=2 to n do
if min>=a[i] then min:=a[i];
//вывод результата
writeln;
write(min);
end.

Заметим, что для нахождения максимального элемента массива достаточно заменить имя переменной min на max и знак >= на знак <=.

Задача 2: Дан одномерный массив, состоящий из n целых чисел. Найти индекс минимального элемент массива. В первой строке вводится количество чисел в массиве n. Затем выводится массив, заданный случайным образом. В третьей строке выводится результат: индекс минимального элемент массива.

Исходные данные:

Результат:

10
5  -2  14  7  -4  23  0  8  6  -1

5

10
0  4  5  2  77  62  4  8  0  45

9

Если в задаче требуется найти индекс минимального (максимального), то вводим переменную imin, в которую будем запоминать индекс минимального (максимального), причем первоначально ее значение равно 1.

program min2;
var a:array[1..100] of integer;
i,min,n,imin:integer;
begin
//заполнение массива и вывод массива в строчку
readln(n);
for i:=1 to n do begin
a[i]:=random(-100,100);
write(a[i],’ ‘);
end;
//нахождение индекса минимального элемента массива
min:=a[1];
imin:=1;
for i:=2 to n do
if min>=a[i] then begin
imin:=i;
min:=a[i];
end;
//вывод результата
writeln;
write(imin);
end.

Если в массиве есть несколько равных между собой минимальных элементов, то данная программа найдет номер последнего (правого) элемента. Для того чтобы найти индекс первого (левого) элемента достаточно изменить знак  >= на строгий знак >.
Эту программу можно оптимизировать, так как, зная индекс минимального элемента, можно найти значение минимального элемента массива. Значит, переменная min не нужна:

var a:array[1..100] of integer;
i,n,imin:integer;

Фрагмент нахождения индекса минимального элемента массива выглядит так:

imin:=1;
for i:=2 to n do
if a[imin]>=a[i] then imin:=i;

Задача 3: Дан одномерный массив, состоящий из n целых чисел. Найти количество минимальных элементов массива. В первой строке вводится количество чисел в массиве n. Затем выводится массив, заданный случайным образом. В третьей строке выводится результат: количество минимальных элементов массива.

Исходные данные:

Результат:

10
5  -2  14  7  -4  23  0  8  -4  -1

2

10
0  4  5  2  77  0  4  8  0  45

3

program min3;
var a:array[1..100] of integer;
i,min,n,k:integer;
begin
//заполнение массива и вывод массива в строчку
readln(n);
for i:=1 to n do begin
a[i]:=random(-5,5);
write(a[i],’ ‘);
end;
//нахождение минимального элемента массива
min:=a[1];
for i:=2 to n do
if min>=a[i] then
min:=a[i];
//считаем количество равных элементов
k:=0;
for i:=1 to n do
if a[i]=min then k:=k+1;
//вывод результата
writeln;
write(k);
end.

Задача 4: Дан целочисленный массив из n элементов. Элементы массива могут принимать целые значения от 0 до 1000. Напишите программу, находящую минимальное значение среди элементов массива, которые имеют чётное значение и не делятся на четыре. Гарантируется, что в исходном массиве есть хотя бы один элемент, значение которого чётно и не кратно четырем. В первой строке вводится количество чисел в массиве n. Затем выводится массив, заданный случайным образом. В третьей строке выводится результат: минимальное значение среди элементов массива, которые имеют чётное значение и не делятся на четыре.

Исходные данные:

Результат:

10
5  -2  14  7  -4  22  0  -8  -6  -1

-6

10
0  4  5  -10  77  0  4  -12  0  45

-10

В этой задаче первый способ нахождения минимального не подойдет. Первый элемент массива может оказаться меньше, чем минимальный четный и не кратный четырем и программа выведет неверный результат. Каким должно быть начальное значение переменной min? Его нужно выбрать таким, чтобы для первого же «подходящего» элемента выполнилось условие a[i] < min, и это «временное» начальное значение было бы заменено на реальное. Такое «подходящее» обязательно будет, так как это гарантировано условием задачи. Оно должно быть большим и таким, какое не может быть по условию задачи, например, 1001.

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

Итак, находим минимальный элемент вторым способом.

2 способ

Записываем в переменную min значение 1001. Затем в цикле просматриваем все элементы массива, с первого до последнего. Если остаток от деления очередного элемента на 2 равен 0 и остаток от его деления на 4 не равен нулю и значение элемента меньше, чем значение переменной min, сохраняем в переменную min значение очередного элемента массива. После окончания работы цикла выводим значение переменной min.

program min4;
var a:array[1..100] of integer;
i,min,n:integer;
begin
//заполнение массива и вывод массива в строчку
readln(n);
for i:=1 to n do
readln(a[i]);
for i:=1 to n do
write(a[i],’ ‘);
//нахождение минимального элемента массива
min:=1001;
for i:=1 to N do
if (a[i] mod 2=0) and (a[i] mod 4 <> 0) and (a[i]<min) then
  min:=a[i];
//вывод результата
writeln;
write(min);
end.

Проверяем на тестах:

10
411 837 755 90 520 203 581 798 401 640

90

10
195 264 127 936 658 152 339 504 395 553

658

 Конечно, решить эту задачу можно и первым способом, но для нахождения первого значения min нужно написать дополнительные команды поиска. Вот таким может быть решение:

program min5;
var a:array[1..100] of integer;
i,min,n,j:integer;
begin
//заполнение массива и вывод массива в строчку
readln(n);
for i:=1 to n do
readln(a[i]);
for i:=1 to n do
write(a[i],’ ‘);
//нахождение первого четного и не кратного 4 числа
i:=1;
while (i<=n)and not((a[i] mod 2=0) and (a[i] mod 4 <> 0)) do i:=i+1;
//в переменной i запомнился номер первого элемента, удовлетворяющего условию
//нахождение минимального, начиная со следующего за найденным
min:=a[i];
for j:=i+1 to N do
if (a[j] mod 2=0) and (a[j] mod 4 <> 0) and (a[j]<min) then
  min:=a[j];
//вывод результата
writeln;
write(min);
end.

Задача 5: Дан целочисленный массив из n элементов. Элементы массива могут принимать произвольные целые значения. Напишите программу, которая находит и выводит второй максимум массива (элемент, который в отсортированном по невозрастанию массиве стоял бы вторым).

Исходные данные:

Результат:

10
5  -2  14  7  -4  22  0  -8  -6  -1

14

10
0  4  5  -10  77  0  4  -12  0  45

45

Мы знаем, как найти первый максимум, а в этой задаче нужно найти второй по величине максимум. Попробуем это сделать это за один проход по массиву. Нам нужны две переменные, max1 (максимальный элемент) и max2 (второй максимум). Сначала выбираем максимальный из первых двух элементов и записываем его значение в max1, а второй по величине записываем в max2.

Затем в цикле перебираем все элементы, начиная с 3-го до последнего. Если очередной элемент a[i] больше, чем max1, записываем значение max1 в max2 (предыдущий максимум становится вторым), а значение a[i] – в max1. Иначе, если a[i] больше, чем max2, записываем значение a[i] в max2. После завершения цикла выводим значение переменной max2.

program min6;
var a: array [1..100] of integer;
i, k,n, max1, max2: integer;
begin
  //заполнение массива и вывод массива в строчку
readln(n);
for i:=1 to n do begin
a[i]:=random(0,100);
write(a[i],’ ‘);
end;
//начальные значения max1 и max2
if a[1] > a[2] then begin
max1:=a[1]; max2:=a[2]
end
else begin
max1:=a[2]; max2:=a[1]
end;
// поиск второго максимального
for i:=3 to N do
if a[i] > max1 then begin
max2:= max1;
max1:= a[i]
end
else
if a[i] > max2 then max2:=a[i];
//вывод результата
writeln;
writeln(max2);
end.

Задача 6: Дан целочисленный массив из 20 элементов. Элементы массива могут принимать целые значения от 1 до 10000 включительно. Напишите программу, позволяющую найти и вывести минимальный элемент массива, шестнадцатеричная запись которого содержит ровно две цифры, причём первая (старшая) цифра больше второй (младшей).  Если таких чисел нет, нужно вывести ответ 0.

Исходные данные:

Результат:

20
5  -2  14  7  -4  22  0  -8  -6  -1

14

10
0  4  5  -10  77  0  4  -12  0  45

45

Эта задача усложнена только тем, что элементы массива должны быть в диапазоне от 16 до 255. В этом случае первая цифра находится как результат деления нацело на 16, а вторая цифра – как остаток от деления на 16.

Кроме этого здесь массив можно объявить через константу n, так как размер массива задан явно: 20 элементов.

program z6;
//объявление массива через константу
const n=20;
var a: array [1..n] of integer;
i,min: integer;
begin
  //заполнение массива и вывод массива в строчку
for i:=1 to n do begin
a[i]:=random(0,10000);
write(a[i],’ ‘);
end;
writeln;
min := 10001;
for i := 1 to n do begin
//для проверки правильности программы выведем две шестнадцатеричные цифры:
//write(a[i] div 16,a[i] mod 16,’ ‘);
if (16 <= a[i]) and (a[i] < 256) and (a[i] div 16 > a[i] mod 16) and (a[i] < min) then
    min := a[i];
end;
writeln;
//вывод результата
if min = 10001 then
  writeln(0)
else
  writeln(min);
end.

Задачи для самостоятельного решения:

  1. Дан целочисленный массив из n элементов. Элементы могут принимать значения от 150 до 210 ­– рост учащихся выпускного класса. В волейбольную команду берут тех, чей рост не менее 170 см. Напишите программу, которая определяет и выводит минимальный рост игрока баскетбольной команды. Гарантируется, что хотя бы один ученик играет в баскетбольной команде.
  2. Дан целочисленный массив из n элементов. Элементы массива могут принимать целые значения от 0 до 100 – баллы учащихся выпускного класса за экзамен по информатике. Для получения положительной оценки за экзамен требовалось набрать не менее 50 баллов. Напишите программу, которая находит и выводит минимальный балл среди учащихся, получивших за экзамен положительную оценку. Известно, что в классе хотя бы один учащийся получил за экзамен положительную оценку.
  3. Дан целочисленный массив – сведения о температуре за каждый день октября. Элементы массива могут принимать целочисленные значение значения от -15 до 20. Напишите программу, которая находит и выводит максимальную температуру среди дней, когда были заморозки (температура опускалась ниже нуля). Гарантируется, что хотя бы один день в октябре была отрицательная температура.
  4. Дан целочисленный массив из n элементов, все элементы которого – неотрицательные числа, не превосходящие 10000. Напишите программу, которая находит и выводит минимальное трехзначное число, записанное в этом массиве. Если таких чисел нет, нужно вывести сообщение «Таких чисел нет».
  5. Дан целочисленный массив из n элементов. Элементы массива могут принимать целые значения от 1 до 10000 включительно. Напишите программу, позволяющую найти и вывести наибольший из элементов массива, шестнадцатеричная запись которого оканчивается на букву F. Если таких чисел нет, нужно вывести ответ 0.
  6. Дан целочисленный массив из n элементов. Элементы массива могут принимать произвольные целые значения. Напишите программу, которая находит и выводит номера двух элементов массива, сумма которых минимальна.
  7. Дан целочисленный массив из 20 элементов. Элементы массива могут принимать целые значения от 1 до 10000 включительно. Напишите программу, находящую минимальный элементов массива, шестнадцатеричная запись которого содержит ровно две цифры, причём вторая (младшая) цифра – это буква (от A до F). Если таких чисел нет, нужно вывести ответ 0.

Источники информации

  1. Угринович Н.Д. Информатика и информационные технологии. Учебник для 10-11 классов/ Н.Д. Угринович. – М.:Бином. Лаборатория знаний, 2005.
  2. Сайт К. Полякова http://kpolyakov.spb.ru/school/ege.htm

Добавить комментарий