Skip to content

Commit 260b818

Browse files
authored
Version (v2.0.0)
1 parent b88bbb1 commit 260b818

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

calculator-v2.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import re
2+
import math
3+
4+
def preprocess(expression):
5+
# Replace caret with exponent operator
6+
expression = expression.replace('^', '**')
7+
8+
# Replace square symbols like 5² with 5**2
9+
expression = re.sub(r'(\d+)²', r'(\1**2)', expression)
10+
11+
# Replace sqrt(x) with math.sqrt(x)
12+
expression = re.sub(r'sqrt\(([^)]+)\)', r'math.sqrt(\1)', expression)
13+
14+
return expression
15+
16+
def is_safe_expression(expr):
17+
# Only allow numbers, operators, parentheses, and valid keywords
18+
return bool(re.match(r'^[\d\s+\-*/().^sqrt²]+$', expr))
19+
20+
def calculate_advanced(expression):
21+
expression = expression.replace(' ', '') # Remove spaces
22+
if not is_safe_expression(expression):
23+
return "? Invalid input! Only numbers and basic operators (plus ^, sqrt, ²) are allowed."
24+
25+
try:
26+
safe_expr = preprocess(expression)
27+
result = eval(safe_expr, {"__builtins__": None, "math": math})
28+
return f"? Result: {result}"
29+
except Exception as e:
30+
return f"?? Error: {e}"
31+
32+
# Example usage
33+
while True:
34+
user_input = input("Enter expression (or 'exit' to quit): ")
35+
if user_input.lower() == 'exit':
36+
break
37+
print(calculate_advanced(user_input))

0 commit comments

Comments
 (0)