mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-02-26 02:48:40 +00:00
ostfix_evaluation.py now supports Unary operators and floating point numbers. Also merged evaluate_postfix_notations.py and postfix_evaluation.py into postfix_evaluation.py which fixes #8724. Added a doctest example with unary operator and invalid expression.
This commit is contained in:
parent
b4f51a6ac3
commit
9a15148f8b
@ -31,7 +31,7 @@ UNARY_OP_SYMBOLS = ("-", "+")
|
|||||||
BINARY_OP_SYMBOLS = ("-", "+", "*", "^", "/")
|
BINARY_OP_SYMBOLS = ("-", "+", "*", "^", "/")
|
||||||
|
|
||||||
|
|
||||||
def parse_token(data: str) -> float | str:
|
def parse_token(token: str | float) -> float | str:
|
||||||
"""
|
"""
|
||||||
Converts the given data to appropriate number if it is indeed a number, else returns
|
Converts the given data to appropriate number if it is indeed a number, else returns
|
||||||
the data as it is with a False flag. This function also serves as a check of whether
|
the data as it is with a False flag. This function also serves as a check of whether
|
||||||
@ -39,25 +39,20 @@ def parse_token(data: str) -> float | str:
|
|||||||
|
|
||||||
Parameters
|
Parameters
|
||||||
----------
|
----------
|
||||||
data : str
|
token : str or float
|
||||||
The data which needs to be converted to the appropriate number
|
The data which needs to be converted to the appropriate number
|
||||||
|
|
||||||
Returns
|
Returns
|
||||||
-------
|
-------
|
||||||
bool, int or float
|
float or str
|
||||||
Returns a tuple of (a, b) where 'a' is True if data is indeed a number (integer
|
Returns a float if `token` is a number and returns `token` if it's an operator
|
||||||
or numeric) and 'b' is either an integer of a floating point number.
|
|
||||||
If 'a' is False, then b is 'data'
|
|
||||||
"""
|
"""
|
||||||
|
if is_operator(token):
|
||||||
|
return token
|
||||||
try:
|
try:
|
||||||
return int(data)
|
return float(token)
|
||||||
except ValueError:
|
except ValueError:
|
||||||
try:
|
msg = f"{token} is neither a number nor a valid operator"
|
||||||
return float(data)
|
|
||||||
except ValueError:
|
|
||||||
if is_operator(data):
|
|
||||||
return data
|
|
||||||
msg = f"{data} is neither a number nor a valid operator"
|
|
||||||
raise ValueError(msg)
|
raise ValueError(msg)
|
||||||
|
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user