Как найти два наибольших числа в python

Можете просто примерно написать как думать, а то вообще идей нет

Total Pusher's user avatar

задан 6 окт 2019 в 6:26

Forer's user avatar

2

first_max = int(input())
second_max = int(input())
if first_max < second_max:
    first_max, second_max = second_max, first_max
element = int(input())
while element != 0:
    if element > first_max:
        second_max, first_max = first_max, element
    elif element > second_max:
        second_max = element
    element = int(input())
print(second_max)

ответ дан 6 окт 2019 в 6:27

Андрей Крузлик's user avatar

Андрей КрузликАндрей Крузлик

1,2633 золотых знака11 серебряных знаков17 бронзовых знаков

Пожалуй эффективнее всего будет воспользоваться функцией heapq.nlargest():

from heapq import nlargest

res = nlargest(2, items)[1]

ответ дан 6 окт 2019 в 7:14

MaxU - stand with Ukraine's user avatar

Можно написать функцию:

def find_maxes(array, count):
    # копируем список чтобы не изменить старую
    copied_array = array.copy()
    maximums = []
    if count > len(copied_array):
        raise ValueError('Количество не может превышать длину списка')
    for _ in range(count):
        max_val = max(copied_array)  # получаем максимальное значение
        copied_array.remove(copied_array)  # удаляем его из списка
        maximums.append(max_val)  # добавляем в наш ожидаемый результат
    return maximums

или же можно поступить хитро

def find_maxes(array, count):
    if count > len(array):
        raise ValueError('Количество не может превышать длину списка')
    sorted_array = sorted(array)  # отсортировать список
    # Забрать последние элементы из спика так как они будут максимальными
    return sorted_array[len(array)-count: len(array)]

ответ дан 6 окт 2019 в 6:44

E1mir's user avatar

E1mirE1mir

1,89811 серебряных знаков23 бронзовых знака

2

b=[3,5,6,7,7,7]

print(list(set(b))[-2])

функция set позволит создать множество отсортированных по возрастанию отличных друг от друга чисел, функция list позволит создать список и обратиться к предпоследнему (или -2) элементу.

<<6

ответ дан 29 окт 2020 в 21:37

FeToR's user avatar

FeToRFeToR

12 бронзовых знака

JacobM’s answer is absolutely the way to go. However, there are a few things to keep in mind while implementing what he described. Here’s a little play-along-at-home tutorial to guide you through the trickier parts of solving this problem.

If this code is meant for production use, please use one of the more efficient/concise answers listed. This answer is targetted at someone new to programming.

The idea

The idea is simple.

  • Keep two variables: largest and second_largest.
  • Go through the list.
    • If an item is greater than largest, assign it to largest.
    • If an item is greater than second_largest, but less than largest, assign it to second_largest.

Getting started

Let’s start.

def two_largest(inlist):
    """Return the two largest items in the sequence. The sequence must
    contain at least two items."""
    for item in inlist:
        if item > largest:
            largest = item
        elif largest > item > second_largest:
            second_largest = item
    # Return the results as a tuple
    return largest, second_largest

# If we run this script, it will should find the two largest items and
# print those
if __name__ == "__main__":
    inlist = [3, 2, 1]
    print two_largest(inlist)

Okay, we now have JacobM’s answer as a Python function. What happens when we try to run it?

Traceback (most recent call last):
  File "twol.py", line 10, in <module>
    print two_largest(inlist)
  File "twol.py", line 3, in two_largest
    if item > largest:
UnboundLocalError: local variable 'largest' referenced before assignment

Apparently, we need to set largest before we start the loop. This probably means we should set second_largest too.

Initializing variables

Let’s set largest and second_largest to 0.

def two_largest(inlist):
    """Return the two largest items in the sequence. The sequence must
    contain at least two items."""
    largest = 0 # NEW!
    second_largest = 0 # NEW!
    for item in inlist:
        if item > largest:
            largest = item
        elif largest > item > second_largest:
            second_largest = item
    # Return the results as a tuple
    return largest, second_largest

# If we run this script, it will should find the two largest items and
# print those
if __name__ == "__main__":
    inlist = [3, 2, 1]
    print two_largest(inlist)

Good. Let’s run it.

(3, 2)

Great! Now let’s test with inlist being [1, 2, 3]

    inlist = [1, 2, 3] # CHANGED!

Let’s try it.

(3, 0)

…Uh oh.

Fixing the logic

The largest value (3) seems correct. The second-largest value is completely wrong though. What’s going on?

Let’s work through what the function is doing.

  • When we start, largest is 0 and second_largest is also 0.
  • The first item in the list we look at is 1, so largest becomes 1.
  • The next item is 2, so largest becomes 2.

But what about second_largest?

When we assign a new value to largest, the largest value actually becomes second-largest. We need to show that in the code.

def two_largest(inlist):
    """Return the two largest items in the sequence. The sequence must
    contain at least two items."""
    largest = 0
    second_largest = 0
    for item in inlist:
        if item > largest:
            second_largest = largest # NEW!
            largest = item
        elif largest > item > second_largest:
            second_largest = item
    # Return the results as a tuple
    return largest, second_largest

# If we run this script, it will should find the two largest items and
# print those
if __name__ == "__main__":
    inlist = [1, 2, 3]
    print two_largest(inlist)

Let’s run it.

(3, 2)

Fantastic.

Initializing variables, part 2

Now let’s try it with a list of negative numbers.

    inlist = [-1, -2, -3] # CHANGED!

Let’s run it.

(0, 0)

That’s not right at all. Where did these zeroes come from?

It turns out that the starting values for largest and second_largest were actually larger than all the items in the list. The first thing you might consider is setting largest and second_largest to the lowest values possible in Python. Unfortunately, Python doesn’t have a smallest possible value. That means that, even if you set both of them to -1,000,000,000,000,000,000, you can have a list of values smaller than that.

So what’s the best thing to do? Let’s try setting largest and second_largest to the first and second items in the list. Then, to avoid double-counting any items in the list, we only look at the part of the list after the second item.

def two_largest(inlist):
    """Return the two largest items in the sequence. The sequence must
    contain at least two items."""
    largest = inlist[0] # CHANGED!
    second_largest = inlist[1] # CHANGED!
    # Only look at the part of inlist starting with item 2
    for item in inlist[2:]: # CHANGED!
        if item > largest:
            second_largest = largest
            largest = item
        elif largest > item > second_largest:
            second_largest = item
    # Return the results as a tuple
    return largest, second_largest

# If we run this script, it will should find the two largest items and
# print those
if __name__ == "__main__":
    inlist = [-1, -2, -3]
    print two_largest(inlist)

Let’s run it.

(-1, -2)

Great! Let’s try with another list of negative numbers.

    inlist = [-3, -2, -1] # CHANGED!

Let’s run it.

(-1, -3)

Wait, what?

Initializing variables, part 3

Let’s step through our logic again.

  • largest is set to -3
  • second_largest is set to -2

Wait right there. Already, this seems wrong. -2 is larger than -3. Is this what caused the problem? Let’s continue.

  • largest is set to -1; second_largest is set to the old value of largest, which is -3

Yes, that looks to be the problem. We need to ensure that largest and second_largest are set correctly.

def two_largest(inlist):
    """Return the two largest items in the sequence. The sequence must
    contain at least two items."""
    if inlist[0] > inlist[1]: # NEW
        largest = inlist[0]
        second_largest = inlist[1]
    else: # NEW
        largest = inlist[1] # NEW
        second_largest = inlist[0] # NEW
    # Only look at the part of inlist starting with item 2
    for item in inlist[2:]:
        if item > largest:
            second_largest = largest
            largest = item
        elif largest > item > second_largest:
            second_largest = item
    # Return the results as a tuple
    return largest, second_largest

# If we run this script, it will should find the two largest items and
# print those
if __name__ == "__main__":
    inlist = [-3, -2, -1]
    print two_largest(inlist)

Let’s run it.

(-1, -2)

Excellent.

Conclusion

So here’s the code, nicely commented and formatted. It’s also had all the bugs I could find beaten from it. Enjoy.

However, assuming this really is a homework question, I hope you get some useful experience from seeing an imperfect piece of code slowly improved. I hope some of these techniques will be useful in future programming assignments.


Efficiency

Not very efficient. But for most purposes, it should be okay: on my computer (Core 2 Duo), a list of 100 000 items can be processed in 0.27 seconds (using timeit, averaged over 100 runs).

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

В этой статье мы расскажем, как можно найти второе по величине число в списке Python с помощью следующих принципов:

  1. Сортировка списка и печать предпоследнего числа списка.
  2. Удаление максимального элемента.
  3. Нахождение максимального элемента.
  4. Перемещение по списку.

Давайте разберем первый подход.

Сортировка списка и печать предпоследнего числа

Следующая программа показывает, как это можно сделать на Python.

Пример –

 
#program to find the second largest number of list 
# declaring the list 
list_val = [20, 30, 40, 25, 10] 
# sorting the list 
list_val.sort() 
#displaying the second last element of the list 
print("The second largest element of the list is:", list_val[-2]) 

Выход:

The second largest element of the list is: 30 

Объяснение –

  1. Мы объявили список, из которого хотим изъять второй элемент, начиная с конца списка.
  2. После этого мы использовали метод сортировки, чтобы все элементы нашего списка располагались в порядке возрастания.
  3. Теперь мы используем отрицательную индексацию, так как второе по величине число будет на предпоследней позиции.

Второй метод – получить второй по величине элемент списка, удалив максимальный элемент.

Давайте посмотрим, как мы можем это сделать.

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

Пример –

 
#program to find the second largest number of list 
 
# declaring the list 
list_val = [20, 30, 40, 25, 10] 
 
# new_list is a set of list1 
res_list = set(list_val) 
 
#removing the maximum element 
res_list.remove(max(res_list)) 
 
#printing the second largest element  
print(max(res_list)) 

Выход:

30 

Объяснение –

Давайте разберемся, что мы сделали в вышеуказанной программе:

  1. Мы объявили список, из которого хотим изъять второй по величине элемент.
  2. После этого мы использовали метод set, чтобы взять все уникальные элементы списка.
  3. Теперь мы используем max(), чтобы получить максимальное значение из списка, а затем удаляем его.
  4. После этого мы печатаем максимум результирующего списка, который даст нам второе по величине число.

В третьем методе мы будем использовать цикл for и и с его помощью найдем второй максимум из списка.

Нахождение максимального элемента

Пример –

 
# declaring empty list 
list_val = [] 
 
# user provides the number of elements to be added in the list 
num_list = int(input("Enter number of elements in list: ")) 
 
 
for i in range(1, num_list + 1): 
 element = int(input("Enter the elements: ")) 
 list_val.append(element) 
 
 
# sort the list 
list_val.sort() 
 
# print second largest element 
print("Second largest element is:", list_val[-2]) 

Выход:

Enter number of elements in list: 5 
 
Enter the elements: 10 
 
Enter the elements: 20 
 
Enter the elements: 30 
 
Enter the elements: 40 
 
Enter the elements: 50 
The second largest element is: 40 

Объяснение –

  1. Мы объявили пустой список, в который будем вставлять элементы.
  2. После этого мы просим пользователя предоставить нам количество элементов, которые мы хотели бы добавить в наш список.
  3. Используем метод сортировки, чтобы все элементы нашего списка располагались в порядке возрастания.
  4. Теперь мы применим отрицательную индексацию, так как второе по величине число будет на второй последней позиции.

Перемещение по списку

В последней программе мы пройдемся по списку, чтобы найти наибольшее число, а затем с помощью условных операторов найдем второе по величине число в списке.

Следующая программа это проиллюстрирует:

 
def calc_largest(arr): 
 second_largest = arr[0] 
 largest_val = arr[0] 
 for i in range(len(arr)): 
 if arr[i] > largest_val: 
 largest_val = arr[i] 
 
 for i in range(len(arr)): 
 if arr[i] > second_largest and arr[i] != largest_val: 
 second_largest = arr[i] 
 
 return second_largest 
print(calc_largest([20, 30, 40, 25, 10])) 

Выход:

30 

Объяснение –

Давайте разберемся, что мы сделали в вышеуказанной программе:

  1. Первый шаг – создать функцию, которая проверяет наибольшее число из списка, просматривая его.
  2. В следующем цикле for мы снова просматриваем список для поиска наибольшего числа, но на этот раз исключаем предыдущий, так как здесь наша цель – найти вторую по величине функцию.
  3. Наконец, мы передаем наш список в функцию.

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

Изучаю Python вместе с вами, читаю, собираю и записываю информацию опытных программистов.

Находит два максимальных числа.

>>> def f(seq):
...     m1 = m2 = None
...     for i in seq:
...         if m2 is None:
...             m2 = i
...         elif m1 is None:
...             if i > m2:
...                 m1, m2 = m2, i
...             else:
...                 m1 = i
...         elif i > m2:
...             m1, m2 = m2, i
...         elif i > m1:
...             m1 = i
...     return (m1, m2)
... 
>>> a = [1, 2, 39, 4, 13, 4, 5, 6, 7, 3, 23, 2]
>>> 
>>> f(a)
(23, 39)
>>>

In this article, we will see how to get the max of two numbers in Python. We have four possible ways to get a maximum of two numbers. We will learn all four methods one by one. I hope you all know that the built-in function is available to get a maximum of two numbers in python. But as python programmers, we have to know the possible ways to do a program without a built-in function. We will also learn about the built-in function and some general methods without using the built-in function. Let us start.

Maximum between two numbers is calculated in python using four different methods. The first one is using a conditional statement, if-else condition to check the maximum element. Secondly, using a built-in function, max(), to get the largest element. Thirdly, by using the ternary operator. And the last method is the lambda function. 

Method 1: Using if-else statement to get max of two numbers in python

if-else is one of the decision-making statements in python. It will check the given condition. If the condition is satisfied, it will return the if part statement. Otherwise, it will return else part statement.

Code

a=int(input("Enter a number: "))
b=int(input("Enter a number: "))
if a>b:
    print(f'{a} is a maximum number')
else:
    print(f'{b} is a maximum number')

This program will get the two inputs from the user to get a maximum element from the given inputs. In an, if statement we are giving a condition like if a>b, print this statement. If not, print the else statement. So it will take the input and print the result after checking with a given condition.

Output

Enter a number: 3
Enter a number: 8
8 is a maximum number

Method 2: Using the max function to get max of two numbers in python

max is a built-in function in python, and that is useful to get the maximum element from the given elements.

Syntax

max(element1,element2)

Parameters

  • element1: first element
  • element2: second element

Returns

maximum element

Code

def maximum(a,b):
    num=max(a,b)
    return num
a=50
b=30
print(f'{maximum(a,b)} is a maximum number')

Creating a function named maximum, and the parameters are a and b. Using a max function to get the larger element. Giving a value of a and b. I always prefer the formatted function to print the result to understand what the program performs without seeing the code.

Output

50 is a maximum number

Efficiently Organize Your Data with Python Trie

Method 3: Using the ternary operator to get max of two numbers in python

The ternary operator is also known as the conditional operator. This operator is useful to check the condition in a single line.

Syntax

[on_true] if [expression] else [on_false] 

Code

a=int(input("Enter a number: "))
b=int(input("Enter a number: "))
print(f'{a if a >= b else b} is a maximum number')

First, get the inputs from the user. Using the ternary operator to get the maximum element from the given numbers.

Output

Enter a number: 40
Enter a number: 75
75 is a maximum number

Method 4: Using lambda function to get max of two numbers in python

A lambda is an anonymous function, and it takes any number of arguments. But the expression is only one.

Syntax

lambda arguments : expression

Code

a=int(input("Enter a number: "))
b=int(input("Enter a number: "))
maximum = lambda a,b:a if a > b else b
print(f'{maximum(a,b)} is a maximum number')

First, get the inputs from the user. Using the lambda function to get the maximum element from the given numbers.

Output

Enter a number: 34
Enter a number: 98
98 is a maximum number

Bonus: How to get a maximum between three numbers

def maximum(a,b,c):
    num=max(a,b,c)
    return num
a=50
b=30
c=80
print(f'{maximum(a,b,c)} is a maximum number')

Creating a function named maximum and the parameters are a, b, and c. Using a max function to get the larger element. Giving a value of a, b, and c. I always prefer the formatted function to print the result to understand what the program performs without seeing the code.

Output

80 is a maximum number

1. In which version of python conditional operator is introduced?

The conditional operator is introduced in a version of 2.5

2. How many arguments does the lambda function takes?

Lambda function takes only one expression.

Conclusion

Here we came to the end of the article. Now we have completely learned about how to get the maximum elements from the given two numbers. We learned all the possible ways to get the maximum element in python.

We hope this article is easy to understand. In case of any queries, feel free to ask in the comment section.

Trending Python Articles

  • Efficiently Organize Your Data with Python Trie

  • [Fixed] modulenotfounderror: no module named ‘_bz2

  • [Fixed] Cannot Set verify_mode to cert_none When check_hostname is Enabled

  • Prevent Errors with Python deque Empty Handling

Понравилась статья? Поделить с друзьями:
  • Как найти подход к дракону
  • Как найти валентность h2so4
  • Как составить смету для видеонаблюдения
  • Как найти хорошего учителя рассказ
  • Как найти на кого подписан на авито