How do I find the maximum of 2 numbers?
PythonMaxPython Problem Overview
How to find the maximum of 2 numbers?
value = -9999
run = problem.getscore()
I need to compare the 2 values i.e value
and run
and find the maximum of 2. I need some python function to operate it?
Python Solutions
Solution 1 - Python
Use the builtin function max
.
Example:
max(2, 4)
returns 4.
Just for giggles, there's a min
as well...should you need it. :P
Solution 2 - Python
Solution 3 - Python
max(number_one, number_two)
Solution 4 - Python
You can use max(value, run)
The function max
takes any number of arguments, or (alternatively) an iterable, and returns the maximum value.
Solution 5 - Python
max(value,run)
should do it.
Solution 6 - Python
Just for the fun of it, after the party has finished and the horse bolted.
The answer is: max()
!
Solution 7 - Python
You could also achieve the same result by using a Conditional Expression:
maxnum = run if run > value else value
a bit more flexible than max
but admittedly longer to type.
Solution 8 - Python
(num1>=num2)*num1+(num2>num1)*num2
will return the maximum of two values.
Solution 9 - Python
I noticed that if you have divisions it rounds off to integer, it would be better to use:
c=float(max(a1,...,an))/b
Sorry for the late post!
Solution 10 - Python
numberList=[16,19,42,43,74,66]
largest = numberList[0]
for num2 in numberList:
if num2 > largest:
largest=num2
print(largest)
gives largest number out of the numberslist without using a Max statement
Solution 11 - Python
# Python 3
value = -9999
run = int(input())
maxnum = run if run > value else value
print(maxnum)
Solution 12 - Python
There are multiple ways to achieve this:
-
Custom method
>
> def maximum(a, b):
> if a >= b:
> return a
> else:
> return b
>
> value = -9999
> run = problem.getscore()
> print(maximum(value, run))
-
Unbuilt max()
> > value = -9999 > run = problem.getscore() > print(max(value, run))
-
Use of ternary operator
> > value = -9999 > run = problem.getscore() > print(value if value >= run else run)
But as you mentioned you are looking for inbuilt so you can use max()