File size: 2,587 Bytes
9b3b8c8
 
 
 
 
 
291349f
9b3b8c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
291349f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db31576
291349f
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
52
53
54
55
56
57
58
59
60
61
62
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."
)