Python maximum and minimum

Asked

Viewed 26,954 times

5

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

3 answers

13

To the minimum it has the function min and to the maximum has the function max.

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

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

Or about an eternal:

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

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

See the example in Ideone

Documentation for the function min and for the function max


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

x = 2
y = 8

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

See also this example in Ideone

9

To title of curiosity, you can implement the function in a mathematical way. It is possible 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 in Ideone | Repl.it

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

  • +1. Very interesting this mathematical deduction to the maximum and minimum that I personally was unaware of.

  • @Isac to make it even more interesting, is it possible to expand to more than two numbers?

  • I think it should be, I’ll see if I can expand logic to 3 elements and possibly deduce a function for N elements in a serial form

  • For 3 elements is easy. Stay: max(a,b,c) = 0.5(a + 0.5(b + c + | b - c|) + | a - 0.5(b + c + |b - c|)|), or in code already def max(a,b,c):&#xA; return 0.5*(a+0.5*(b+c+abs(b-c))+abs(a-0.5*(b+c+abs(b-c)))). Now to N it seems more complicated already

1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.