Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- import re
- import string
- def remove_whitespace(in_string: str):
- return in_string.translate(str.maketrans(dict.fromkeys(string.whitespace)))
- def parse_operation(expression):
- # convert to string
- ss = f"{expression}"
- ss = remove_whitespace(ss)
- # passed value is a simple int or float
- try:
- return int(ss)
- except Exception:
- pass
- try:
- return float(ss)
- except Exception:
- pass
- # passed value is either int or float followed by a %
- match = re.fullmatch(r"([\d]+(\.[\d]+)?)%", ss)
- if match:
- try:
- return int(match.group(1))
- except Exception:
- return float(match.group(1))
- # passed value is (int/float)(operator)(int/float)
- match_list = []
- match_list.append(re.fullmatch(r"([\d]+)%?([+\-*/])([\d]+)%?", ss))
- match_list.append(re.fullmatch(r"([\d]+\.[\d]+)%?([+\-*/])([\d]+\.[\d]+)%?", ss))
- for match in match_list:
- if match:
- try:
- x = int(match.group(1))
- y = int(match.group(3))
- except Exception:
- x = float(match.group(1))
- y = float(match.group(3))
- operator = match.group(2)
- if operator == '+':
- return x + y
- elif operator == '-':
- return x - y
- elif operator == '*':
- return x * y
- elif operator == '/':
- return x / y
- return None
- l1 = ['0', '10+7', '20', '30', '40+20', '6']
- l2 = [0, '10+7', 20, 30, '40+20', 6]
- l1_result = [parse_operation(x) for x in l1]
- l2_result = [parse_operation(x) for x in l2]
- print("l1", l1_result)
- print("l2", l2_result)
- l3 = ['10%', '20%', 5, 14, 16]
- l4 = ['10%+30%', '20%-7%', '5', '14', '16']
- l3_result = [parse_operation(x) for x in l3]
- l4_result = [parse_operation(x) for x in l4]
- print("l3", l3_result)
- print("l4", l4_result)
- l5 = ['10% - 90%', '15.99 + 33.0', '12 / 3', '99 / 34', '25 * 4', '5', '6', '9.99']
- l5_result = [parse_operation(x) for x in l5]
- print("l5", l5_result)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement