counting / maths /algebra /polynomial_operations.py
spagestic's picture
feat: implement Gradio interfaces for algebra operations and create tabbed interface
fe0557b
"""
Performs addition, subtraction, or multiplication of two polynomials.
Polynomials are represented by lists of coefficients in descending order of power.
Example: [1, -2, 3] represents x^2 - 2x + 3.
"""
import gradio as gr
def polynomial_operations(poly1_coeffs: list[float], poly2_coeffs: list[float], operation: str) -> str:
if not all(isinstance(c, (int, float)) for c in poly1_coeffs) or \
not all(isinstance(c, (int, float)) for c in poly2_coeffs):
return "Error: All coefficients must be numbers."
if not poly1_coeffs:
poly1_coeffs = [0]
if not poly2_coeffs:
poly2_coeffs = [0]
op = operation.lower()
if op == "add":
len1, len2 = len(poly1_coeffs), len(poly2_coeffs)
max_len = max(len1, len2)
p1 = [0]*(max_len - len1) + poly1_coeffs
p2 = [0]*(max_len - len2) + poly2_coeffs
result_coeffs = [p1[i] + p2[i] for i in range(max_len)]
elif op == "subtract":
len1, len2 = len(poly1_coeffs), len(poly2_coeffs)
max_len = max(len1, len2)
p1 = [0]*(max_len - len1) + poly1_coeffs
p2 = [0]*(max_len - len2) + poly2_coeffs
result_coeffs = [p1[i] - p2[i] for i in range(max_len)]
elif op == "multiply":
len1, len2 = len(poly1_coeffs), len(poly2_coeffs)
result_coeffs = [0] * (len1 + len2 - 1)
for i in range(len1):
for j in range(len2):
result_coeffs[i+j] += poly1_coeffs[i] * poly2_coeffs[j]
else:
return "Error: Invalid operation. Choose 'add', 'subtract', or 'multiply'."
if not result_coeffs or all(c == 0 for c in result_coeffs):
return "0"
terms = []
degree = len(result_coeffs) - 1
for i, coeff in enumerate(result_coeffs):
power = degree - i
if coeff == 0:
continue
term_coeff = ""
if coeff == 1 and power != 0:
term_coeff = ""
elif coeff == -1 and power != 0:
term_coeff = "-"
else:
term_coeff = str(coeff)
if isinstance(coeff, float) and coeff.is_integer():
term_coeff = str(int(coeff))
if power == 0:
terms.append(term_coeff)
elif power == 1:
terms.append(f"{term_coeff}x")
else:
terms.append(f"{term_coeff}x^{power}")
result_str = terms[0]
for term in terms[1:]:
if term.startswith("-"):
result_str += f" - {term[1:]}"
else:
result_str += f" + {term}"
return result_str
def parse_coeffs(coeff_str: str) -> list[float]:
"""Helper to parse comma-separated coefficients from string input."""
if not coeff_str.strip():
return [0.0]
try:
return [float(x.strip()) for x in coeff_str.split(',') if x.strip() != '']
except ValueError:
# Return a value that indicates error, Gradio will show the function's error message
raise gr.Error("Invalid coefficient input. Ensure all coefficients are numbers.")
polynomial_interface = gr.Interface(
fn=lambda p1_str, p2_str, op: polynomial_operations(parse_coeffs(p1_str), parse_coeffs(p2_str), op),
inputs=[
gr.Textbox(label="Polynomial 1 Coefficients (comma-separated, highest power first, e.g., 1,-2,3 for x²-2x+3)"),
gr.Textbox(label="Polynomial 2 Coefficients (comma-separated, e.g., 2,5 for 2x+5)"),
gr.Radio(choices=["add", "subtract", "multiply"], label="Operation")
],
outputs="text",
title="Polynomial Operations",
description="Add, subtract, or multiply two polynomials. Enter coefficients in descending order of power."
)
if __name__ == "__main__":
polynomial_interface.launch()