Maximum and minimum Python

2

What is the function that I use to find the maximum and minimum values between 2 values in the Python language? Thank you

    
asked by anonymous 29.09.2017 / 05:05

3 answers

8

For the minimum it has the function min and for the maximum it has the function max .

They can be used over 2 (or more) values, the case of the question:

menor = min(2,8) # 2
maior = max(2,8) # 8

Or about an iterable:

lista = [1, 8, 2, 4, 9]

menor = min(lista) # 1
maior = max(lista) # 9

See the Ideone example

Documentation for the function min and for the max

For the simple example of a maximum or minimum of 2 values you could even "hand" based on if :

x = 2
y = 8

menor = x if x < y else y # 2
maior = x if x > y else y # 8

See this example on Ideone

    
29.09.2017 / 11:44
5

A curiosity title , you can implement the function in a mathematical way. It is able to demonstrate that:

max{a, b} = 0.5 (a + b + |a - b|)

and

min{a, b} = 0.5 (a + b - |a - b|)

So in Python, a solution would be:

def minmax(a, b):
    return 0.5*(a+b+abs(a-b)), 0.5*(a+b-abs(a-b))

print(minmax(7, 3)) # (3.0, 7.0)

See working at Ideone | Repl.it

In practice, prefer to use the min and max functions pointed to by Isac .

    
29.09.2017 / 12:28
1

Hi,

Maximum: max () link

Minimum: min () link

    
29.09.2017 / 05:10