counting / maths /arithmetic /calculate_array.py
spagestic's picture
feat: simplify descriptions and examples in Gradio interfaces for arithmetic and calculus tools
db31576
from .add import add
from .subtract import subtract
from .multiply import multiply
from .divide import divide
import gradio as gr
def calculate_array(numbers: list, operations: list) -> float:
"""
Perform a sequence of arithmetic operations on an array of numbers.
Example: numbers=[2, 3, 4], operations=['add', 'multiply'] means (2 + 3) * 4
Supported operations: 'add', 'subtract', 'multiply', 'divide'
"""
if not numbers or not operations:
raise ValueError("Both numbers and operations must be provided and non-empty.")
if len(operations) != len(numbers) - 1:
raise ValueError("Number of operations must be one less than number of numbers.")
result = float(numbers[0])
for i, op in enumerate(operations):
num = float(numbers[i+1])
if op == 'add':
result = add(result, num)
elif op == 'subtract':
result = subtract(result, num)
elif op == 'multiply':
result = multiply(result, num)
elif op == 'divide':
result = divide(result, num)
if isinstance(result, str):
return result
else:
raise ValueError(f"Unsupported operation: {op}")
return result
array_calc_interface = gr.Interface(
fn=lambda numbers, operations: calculate_array(numbers, operations),
inputs=[
gr.Textbox(label="Numbers (comma-separated, e.g. 2, 3, 4)"),
gr.Textbox(label="Operations (comma-separated, e.g. add, multiply)")
],
outputs="text",
title="Array Calculation",
description="Calculate a sequence of numbers with specified operations. Example: Numbers: 2, 3, 4; Operations: add, multiply → (2 + 3) * 4"
)