Given two numbers, write a Python code to find the Maximum of these two numbers.
Examples:
Input: a = 2, b = 4
Output: 4
Input: a = -1, b = -4
Output: -1
Find Maximum of two numbers in Python
This is the naive approach where we will compare two numbers using if-else statement and will print the output accordingly.
Example:
Python3
def maximum(a, b):
if a >= b:
return a
else:
return b
a = 2
b = 4
print(maximum(a, b))
|
Time complexity: O(1)
Auxiliary space: O(1)
Find Maximum of two numbers Using max() function
This function is used to find the maximum of the values passed as its arguments.
Example:
Python3
a = 2
b = 4
maximum = max(a, b)
print(maximum)
|
Time complexity: O(1)
Auxiliary space: O(1)
This operator is also known as conditional expression are operators that evaluate something based on a condition being true or false. It simply allows testing a condition in a single line
Example:
Python3
a = 2
b = 4
print(a if a >= b else b)
|
Time complexity: O(1)
Auxiliary space: O(1)
Maximum of two numbers Using lambda function
Python3
a=2;b=4
maximum = lambda a,b:a if a > b else b
print(f'{maximum(a,b)} is a maximum number')
|
Output:
4 is a maximum number
Maximum of two numbers Using list comprehension
Python3
a=2;b=4
x=[a if a>b else b]
print("maximum number is:",x)
|
Output
maximum number is: [4]
Maximum of two numbers Using sort() method
Python3
a = 2
b = 4
x=[a,b]
x.sort()
print(x[-1])
|
Time Complexity : O(NlogN)
Auxiliary Space : O(1)
Don't miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills and become a part of the hottest trend in the 21st century.
Dive into the future of technology - explore the Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.
Last Updated :
03 Jul, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...