Given two numbers num1 and num2, write a Python program to find the maximum of two numbers.
Example: Input: num1 = 10, num2 = 15 Output: 15 Input: num1 = -5, num2 = -2 Output: -2
Approach 1: Comparing two numbers using the if..else statement.
Explanation:
- In the first two lines, the program takes input for two numbers.
- In the next few lines, the program uses an if statement to compare the two numbers and find the maximum.
- Finally, the program prints the result.
Python Example Code:
# take input for the two numbers num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) # compare the two numbers and find the maximum if num1 > num2: maximum = num1 else: maximum = num2 # print the result print("The maximum number is", maximum)
Enter first number: 10
Enter second number: 15
The maximum number is 15
- Time Complexity: O(1)
- Space Complexity: O(1)
Approach 2: Using the max() function. This function returns the maximum of the values passed as its arguments.
Explanation:
- The first two lines are the same, taking input for the two numbers.
- In the next line, the program uses the max() function to find the maximum of the two numbers.
- Finally, the program prints the result.
Python Example Code:
# take input for the two numbers num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) # use the max function to find the maximum of the two numbers maximum = max(num1, num2) # print the result print("The maximum number is", maximum)
Output:
Enter first number: -10
Enter second number: -15
The maximum number is 10
- Time Complexity: O(1)
- Space Complexity: O(1)
No comments:
Post a Comment