Spaces:
Runtime error
Runtime error
File size: 1,448 Bytes
f11fed1 57fd4f3 f11fed1 57fd4f3 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
from transformers import Tool
def simple_calculator(expression):
# Find the index of the operator
operator_index = -1
for i, char in enumerate(expression):
if char in ('+', '-', '*', '/'):
operator_index = i
break
# Ensure that an operator was found
if operator_index == -1:
return "Invalid expression"
# Split the expression into the operator and operands
operator = expression[operator_index]
operand1 = float(expression[:operator_index])
operand2 = float(expression[operator_index + 1:])
# Perform the calculation based on the operator
if operator == '+':
result = operand1 + operand2
elif operator == '-':
result = operand1 - operand2
elif operator == '*':
result = operand1 * operand2
elif operator == '/':
result = operand1 / operand2
else:
raise ValueError("Input string is not a valid mathematical expression.")
# Convert the result to a string and return it
return str(result)
# Test the function
expression = "1+3"
result = simple_calculator(expression)
class SimpleCalculatorTool(Tool):
name = "simple_calculator"
description = (
"This is a tool that returns the result of a simple mathematical expression written in a string."
)
inputs = ["text"]
outputs = ["text"]
def __call__(self, input_str: str):
return simple_calculator(input_str)
|