Spaces:
Runtime error
Runtime error
import matplotlib.pyplot as plt | |
from .add import add | |
from .subtract import subtract | |
from .multiply import multiply | |
from .divide import divide | |
from .number_line_visualization import create_number_line_visualization | |
import gradio as gr | |
def calculate_array_with_visualization(numbers: list, operations: list) -> tuple: | |
""" | |
Perform a sequence of arithmetic operations on an array of numbers and return result with visualization. | |
Visualization shows the step-by-step calculation on a number line. | |
""" | |
if not numbers or not operations: | |
return "Error: Both numbers and operations must be provided and non-empty.", None | |
if len(operations) != len(numbers) - 1: | |
return "Error: Number of operations must be one less than number of numbers.", None | |
step_results = [float(numbers[0])] | |
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, None | |
else: | |
return f"Error: Unsupported operation: {op}", None | |
step_results.append(result) | |
fig = create_number_line_visualization(numbers, ' -> '.join(operations), result) | |
return result, fig | |
def parse_number_list(s): | |
"""Helper to parse comma-separated numbers from string input.""" | |
try: | |
return [float(x.strip()) for x in s.split(',') if x.strip() != ''] | |
except Exception: | |
return [] | |
def parse_operation_list(s): | |
"""Helper to parse comma-separated operations from string input.""" | |
ops = [x.strip().lower() for x in s.split(',') if x.strip() != ''] | |
valid_ops = {'add', 'subtract', 'multiply', 'divide'} | |
return [op for op in ops if op in valid_ops] | |
array_calc_vis_interface = gr.Interface( | |
fn=lambda numbers, operations: calculate_array_with_visualization( | |
parse_number_list(numbers), parse_operation_list(operations)), | |
inputs=[ | |
gr.Textbox(label="Numbers (comma-separated, e.g. 2, 3, 4)"), | |
gr.Textbox(label="Operations (comma-separated, e.g. add, multiply)") | |
], | |
outputs=[gr.Textbox(label="Result"), gr.Plot(label="Visualization")], | |
title="Array Calculation with Visualization", | |
description="Calculate a sequence of numbers with specified operations and see a number line visualization." | |
) | |