Python Implement a Function That Outputs the Two Largest Values in a List of Numbers
We will write a Python function that takes a list of numbers as input and returns the two largest values in that list. We will implement this with simple logic.
Example
def
find_two_max
(
numbers
)
:
if
len
(
numbers
)
first_max:
second_max
=
first_max
first_max
=
number
elif
number >
;
second_max:
second_max
=
number
return
first_max
,
second_max
Example usage
numbers
=
[
10
,
20
,
4
,
45
,
99
,
99
]
(
find_two_max
(
numbers
)
)
Code analysis:
- First, we check whether the length of the list is less than 2. If so, we return an error message, because we need at least two numbers to find the two largest values.
- We initialize
first_maxandsecond_maxto negative infinity, so that any number in the list will be greater than these two initial values. - We iterate over each number in the list. If the current number is greater than
first_max, wefirst_maxassign the value of tosecond_max, then assign the current number tofirst_max. If the current number is not greater thanfirst_maxbut is greater thansecond_max, we only updatesecond_max。 - Finally, we return
first_maxandsecond_max。
Output result:
Example
(
99
,
99
)
Python3 Examples