Python: Check the priority of the four operators
Python Basic - 1: Exercise-15 with Solution
Write a Python program to check the priority of the four operators (+, -, *, /).
Sample Solution:
Python Code:
# Import the 'deque' class from the 'collections' module and the 're' module for regular expressions.
from collections import deque
import re
# Define operators, parentheses, and operator priorities.
__operators__ = "+-/*"
__parenthesis__ = "()"
__priority__ = {
'+': 0,
'-': 0,
'*': 1,
'/': 1,
}
# Define a function 'test_higher_priority' to compare the priorities of two operators.
def test_higher_priority(operator1, operator2):
# Return True if the priority of 'operator1' is higher than or equal to 'operator2'.
return __priority__[operator1] >= __priority__[operator2]
# Test the function with different operator pairs and print the results.
print(test_higher_priority('*','-'))
print(test_higher_priority('+','-'))
print(test_higher_priority('+','*'))
print(test_higher_priority('+','/'))
print(test_higher_priority('*','/'))
Sample Output:
True True False False True
Explanation:
The above Python code defines a function "test_higher_priority()" that compares the priorities of two mathematical operators (+, -, *, /). Priorities are predefined in the "priority" dictionary. The function returns 'True' if the priority of the first operator is higher than or equal to the priority of the second operator.
Flowchart:
Python Code Editor :
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python program to add two positive integers without using the '+' operator.
Next: Write a Python program to get the third side of right angled triangle from two given sides.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-exercises/basic/python-basic-1-exercise-15.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics