Spaces:
Running
Running
import itertools | |
import gradio as gr | |
def solve_cryptarithm(equation): | |
# Remove spaces from user input | |
equation = equation.replace(" ", "") | |
# Split the equation into left and right sides | |
left_side, right_side = equation.split('=') | |
# Get all unique letters from the equation | |
letters = set(filter(str.isalpha, equation)) | |
letters = ''.join(letters) | |
# If there are too many letters (more than 10), it's impossible to solve | |
if len(letters) > 10: | |
return "Too many letters to solve!" | |
# Get all unique digit combinations for the letters | |
digits = '0123456789' | |
for perm in itertools.permutations(digits, len(letters)): | |
# Create mapping of letters to numbers | |
translation = str.maketrans(letters, ''.join(perm)) | |
# Translate the equation to numbers | |
translated_left_side = left_side.translate(translation) | |
translated_right_side = right_side.translate(translation) | |
# Check if there are numbers starting with 0 | |
if any(part.startswith('0') and len(part) > 1 for part in translated_left_side.split('+') + translated_right_side.split('+')): | |
continue | |
try: | |
# Evaluate whether the left side equals the right side | |
if eval(translated_left_side) == eval(translated_right_side): | |
return f"Solution found: {translated_left_side} = {translated_right_side}" | |
except Exception as e: | |
continue | |
return "No solution found." | |
def solve_multiple_equations(equations): | |
results = [] | |
for equation in equations.splitlines(): | |
if equation.strip(): # Only process non-empty lines | |
result = solve_cryptarithm(equation) | |
results.append(result) | |
return "\n".join(results) | |
# Create Gradio interface | |
iface = gr.Interface( | |
fn=solve_multiple_equations, | |
inputs=gr.Textbox(lines=10, placeholder="Enter one or more cryptarithm equations here..."), | |
outputs="text", | |
title="Cryptarithm Solver", | |
description="Enter cryptarithm equations (e.g., SEND + MORE = MONEY) on each line." | |
) | |
if __name__ == "__main__": | |
iface.launch() | |