Saturday, November 16, 2024
Google search engine
HomeLanguagesMinimum of two numbers in Python

Minimum of two numbers in Python

Given two numbers, write a Python code to find the Minimum of these two numbers. Examples:

Input: a = 2, b = 4
Output: 2

Input: a = -1, b = -4
Output: -4

Method #1: This is the naive approach where we will compare the numbers using if-else statement and will print the output accordingly. Example: 

Python3




# Python program to find the
# minimum of two numbers
 
 
def minimum(a, b):
     
    if a <= b:
        return a
    else:
        return b
     
# Driver code
a = 2
b = 4
print(minimum(a, b))


Output:

2

Time Complexity: O(1)
Auxiliary Space: O(1)

Method #2: Using min() function This function is used to find the minimum of the values passed as its arguments. Example: 

Python3




# Python program to find the
# minimum of two numbers
 
 
a = 2
b = 4
 
minimum = min(a, b)
print(minimum)


Output

2

Time Complexity: O(1)
Auxiliary Space: O(1)

METHOD 3: Using sorted() function

APPROACH:

The code snippet sorts the given two numbers in ascending order and returns the first element, which is the minimum of the two.

ALGORITHM:

1.Initialize variables a and b with the given two numbers.
2.Create a list with the two numbers and sort the list in ascending order using the sorted() function.
3.Retrieve the first element of the sorted list using indexing and assign it to the minimum variable.
4.Print the minimum variable.

Python3




a = 2
b = 4
print(sorted([a, b])[0])


Output

2

Time complexity:
The time complexity of the code is O(1) due to the use of the sorted() function.

Space complexity:
The space complexity of the code is O(1) due to the use of the list to store the two numbers

METHOD 4:Using reduce function.

APPROACH:

This program finds the minimum of two numbers using the reduce function of functools module.

ALGORITHM:

1. Import the reduce function from the functools module.
2. Define the two numbers, a and b.
3. Apply the reduce function with a lambda function that compares the two numbers and returns the minimum.
4. Print the result.

Python3




from functools import reduce
 
a = 2
b = 4
minimum = reduce(lambda x, y: x if x < y else y, [a, b])
print(minimum)


Output

2

Time Complexity: O(1), as it only involves the comparison of two numbers.
Space Complexity: O(1), as it only uses constant amount of memory for the two numbers and the minimum value.

RELATED ARTICLES

Most Popular

Recent Comments