Maximum of two numbers in Python
Given two numbers, write a Python code to find the Maximum of these two numbers.
Examples:
Input: a = 2, b = 4
Output: 4Input: a = -1, b = -4
Output: -1
Method #1: This is the naive approach where we will compare two numbers using if-else statement and will print the output accordingly.
Example:
Python3
# Python program to find the# maximum of two numbersdef maximum(a, b): if a >= b: return a else: return b # Driver codea = 2b = 4print(maximum(a, b)) |
4
Time complexity: O(1)
Auxiliary space: O(1)
Method #2: Using max() function
This function is used to find the maximum of the values passed as its arguments.
Example:
Python3
# Python program to find the# maximum of two numbersa = 2b = 4maximum = max(a, b)print(maximum) |
4
Time complexity: O(1)
Auxiliary space: O(1)
Method #3: Using Ternary Operator
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
# Python program to find the# maximum of two numbers # Driver codea = 2b = 4# Use of ternary operatorprint(a if a >= b else b)# This code is contributed by AnkThon |
4
Time complexity: O(1)
Auxiliary space: O(1)
Method: Using lambda function
Python3
# python code to find maximum of two numbersa=2;b=4maximum = lambda a,b:a if a > b else bprint(f'{maximum(a,b)} is a maximum number') |
4 is a maximum number
Method: Using list comprehension
Python3
a=2;b=4x=[a if a>b else b]print("maximum number is:",x) |
maximum number is: [4]
Method : Using sort() method
Python3
# Python program to find the# maximum of two numbersa = 2b = 4x=[a,b]x.sort()print(x[-1]) |
4
Time Complexity : O(NlogN)
Auxiliary Space : O(1)






Please Login to comment...