What is the function that I use to find the maximum and minimum values between 2 values in the Python language? Thank you
What is the function that I use to find the maximum and minimum values between 2 values in the Python language? Thank you
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
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
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 .