import gradio as gr from itertools import permutations def solve_cryptarithm(equation): # Parse the words from the equation left, right = equation.split(" = ") words = left.split(" + ") + [right] # Extract unique letters unique_letters = set("".join(words)) if len(unique_letters) > 10: return "Error: More than 10 unique letters in equation, unsolvable with digits 0-9." # Helper function to convert words to numbers based on current letter-to-digit mapping def word_to_number(word, mapping): return int("".join(str(mapping[char]) for char in word)) # Depth-First Search with Pruning def dfs(index, letter_to_digit, used_digits): if index == len(unique_letters): left_sum = sum(word_to_number(word, letter_to_digit) for word in words[:-1]) right_val = word_to_number(words[-1], letter_to_digit) return left_sum == right_val # Current letter to assign letter = unique_letters_list[index] # Try every digit for this letter for digit in range(10): # Prune: skip used digits if digit in used_digits: continue # Map the letter to the current digit letter_to_digit[letter] = digit used_digits.add(digit) # Recursive DFS call if dfs(index + 1, letter_to_digit, used_digits): return True # Backtrack del letter_to_digit[letter] used_digits.remove(digit) return False # Main DFS invocation unique_letters_list = list(unique_letters) letter_to_digit = {} used_digits = set() # Start DFS and find solution if dfs(0, letter_to_digit, used_digits): # Format the solution as per the user's requirements formatted_result = "Input: " + equation + "\n\n" for word in words: formatted_result += " ".join(str(letter_to_digit[char]) for char in word) + " " if word != words[-1]: formatted_result += "+ " if word != words[-2] else "= " return formatted_result else: return "No solution found" def process_input(equations): results = [] for equation in equations.splitlines(): result = solve_cryptarithm(equation.strip()) results.append(result) return "\n\n".join(results) interface = gr.Interface( fn=process_input, inputs=gr.Textbox(label="Enter Cryptarithm Equations (one per line)", placeholder="E.g., SEND + MORE = MONEY"), outputs="text", title="Cryptarithm Solver", description="Enter cryptarithm equations (like SEND + MORE = MONEY) one per line to find solutions. Each letter represents a unique digit from 0-9." ) interface.launch()