import math
import random
def addition(a, b):
return a + b
def subtraction(a, b):
return a - b
def multiplication(a, b):
return a * b
def division(a, b):
if b == 0:
raise ValueError("Division by zero")
return a / b
def percentage(a):
return a / 100
def power(a, b):
return a ** b
def square_root(a):
return math.sqrt(a)
def logarithm(a, b):
return math.log(a, b)
def factorial(a):
if a < 0:
raise ValueError("Factorial of negative number")
elif a == 0:
return 1
else:
return a * factorial(a-1)
def sin(a):
return math.sin(math.radians(a))
def cos(a):
return math.cos(math.radians(a))
def tan(a):
return math.tan(math.radians(a))
def asin(a):
return math.degrees(math.asin(a))
def acos(a):
return math.degrees(math.acos(a))
def atan(a):
return math.degrees(math.atan(a))
def sinh(a):
return math.sinh(a)
def cosh(a):
return math.cosh(a)
def tanh(a):
return math.tanh(a)
def asinh(a):
return math.asinh(a)
def acosh(a):
return math.acosh(a)
def atanh(a):
return math.atanh(a)
functions = {
"+": addition,
"-": subtraction,
"*": multiplication,
"/": division,
"%": percentage,
"x^y": power,
"sqrt": square_root,
"log": logarithm,
"n!": factorial,
"sin": sin,
"cos": cos,
"tan": tan,
"asin": asin,
"acos": acos,
"atan": atan,
"sinh": sinh,
"cosh": cosh,
"tanh": tanh,
"asinh": asinh,
"acosh": acosh,
"atanh": atanh
}
special_functions = {
"2nd": {
"sin": asin,
"cos": acos,
"tan": atan,
"sinh": asinh,
"cosh": acosh,
"tanh": atanh,
"sqrt": lambda a: a ** 0.5,
"log": lambda a: math.log10(a),
"ln": lambda a: math.log(a)
},
"x^2": lambda a: power(a, 2),
"x^3": lambda a: power(a, 3),
"x^y": power,
"10^x": lambda a: power(10, a),
"1/x": lambda a: division(1, a),
"2/x": lambda a: division(2, a),
"3/x": lambda a: division(3, a),
"e^x": lambda a: math.exp(a),
"e": lambda _: math.e,
"x!": factorial,
"√": square_root,
"sin": sin,
"cos": cos,
"tan": tan,
"e^x": lambda a: math.exp(a),
"EE": lambda a, b: a * 10 ** b,
"Rad": math.radians,
"sinh": sinh,
"cosh": cosh,
"tanh": tanh,
"π": lambda _: math.pi,
"Rand": lambda _: random.random()
}
def compute(expression):
try:
result = eval(expression, {"builtins": None}, functions)
return result
except Exception as e:
raise ValueError(str(e))
def process_function(func, stack):
if func in special_functions:
current_special_functions = special_functions[func]
while len(stack) > 0 and type(stack[-1]) == str and stack[-1] in current_special_functions:
stack_func = stack.pop()
func = current_special_functions[stack_func]
args = []
while len(stack) > 0 and type(stack[-1]) != str:
args.append(stack.pop())
args = list(reversed(args))
result = func(*args)
stack.append(result)
def process_operator(operator, stack):
op2 = stack.pop()
op1 = stack.pop()
result = functions[operator](op1, op2)
stack.append(result)
def tokenize(expression):
operators = "+-/%()"
delimiters = operators + " "
tokens = []
parens = 0
last_token = None
i = 0
while i < len(expression):
c = expression[i]
if c.isdigit() or c == ".":
if last_token == ")" or last_token in functions:
tokens.append("")
if len(tokens) > 0 and tokens[-1] == ".":
raise ValueError("Invalid decimal")
start = i
while i < len(expression) and (expression[i].isdigit() or expression[i] == "."):
i += 1
end = i
tokens.append(float(expression[start:end]))
i -= 1
elif c in operators:
if c == "-" and (last_token is None or last_token == "(" or last_token in functions):
if len(tokens) > 0 and tokens[-1] == "-":
tokens.pop()
tokens.append("+")
else:
tokens.append("-1.0")
tokens.append("*")
else:
if c == "(":
parens += 1
elif c == ")":
parens -= 1
if parens < 0:
raise ValueError("Mismatched parentheses")
if c == "%" and (last_token is None or last_token in operators):
raise ValueError("Invalid operator")
tokens.append(c)
elif c.isalpha():
start = i
while i < len(expression) and expression[i].isalpha():
i += 1
func_name = expression[start:i]
if func_name in special_functions:
tokens.append("2nd")
tokens.append(func_name)
i -= 1
elif c in delimiters:
pass
else:
raise ValueError("Invalid character: " + c)
last_token = c
i += 1
if parens != 0:
raise ValueError("Mismatched parentheses")
return tokens
def infix_to_postfix(tokens):
precedence = {
"+": 1,
"-": 1,
"*": 2,
"/": 2,
"%": 2,
"(": 0,
")": 0
}
postfix = []
stack = []
for token in tokens:
if type(token) == float:
postfix.append(token)
elif token in functions:
stack.append(token)
elif token in special_functions:
stack.append(token)
elif token == ",":
while len(stack) > 0 and stack[-1] != "(":
postfix.append(stack.pop())
elif token in precedence:
while len(stack) > 0 and stack[-1] != "(" and precedence[stack[-1]] >= precedence[token]:
postfix.append(stack.pop())
stack.append(token)
elif token == "(":
stack.append(token)
elif token == ")":
while len(stack) > 0 and stack[-1] != "(":
postfix.append(stack.pop())
if len(stack) == 0:
raise ValueError("Mismatched parentheses")
stack.pop()
else:
raise ValueError("Invalid token: " + token)
while len(stack) > 0:
if stack[-1] == "(" or stack[-1] == ")":
raise ValueError("Mismatched parentheses")
postfix.append(stack.pop())
return postfix
def evaluate(expression):
tokens = tokenize(expression)
postfix = infix_to_postfix(tokens)
stack = []
for token in postfix:
if type(token) == float:
stack.append(token)
elif token in functions:
process_function(token, stack)
elif token in special_functions:
stack.append(token)
else:
process_operator(token, stack)
if len(stack) != 1 or type(stack[0]) != float:
raise ValueError("Invalid expression")
return stack[0]
def help():
print("""
Welcome to the Calculator program!
This calculator supports the following functions:
+, -, *, /, %, x^y, sqrt, log, n!, sin, cos, tan, asin, acos, atan,
sinh, cosh, tanh, asinh, acosh, atanh, 2nd, x^2, x^3, 10^x, 1/x, 2/x, 3/x,
e^x, e, x!, √, π, Rand, Rad, ln, EE
Usage: Enter an expression to get the result. Functions are entered using
their full name (e.g. sin) or their shortcut (e.g. s). To use a special
function, first enter the 2nd key.
Examples:
2 + 2
sin(90)
sqrt(4) * 2
x^2(3)
log(100, 10)
1 + 2 * 3 - 4 / 5
2nd -> e^x(1)")
""")
help()
while True:
try:
expression = input("> ")
if expression == "exit":
break
elif expression == "help":
help()
else:
result = evaluate(expression)
print(result)
except Exception as e:
print("Error: " + str(e))
完善一下这个代码