kendrickfff's picture
fix the DFS algorithm
3ca8c04 verified
raw
history blame
3.41 kB
import gradio as gr
def solve_cryptarithm(equation):
# Parse the words from the equation "SEND + MORE = MONEY"
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 we've assigned all letters, check if equation holds
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 and avoid leading zero for multi-letter words
if digit in used_digits or (digit == 0 and letter_is_leading[letter]):
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
# Identify which letters are leading letters in each word
letter_is_leading = {word[0]: True for word in words}
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 = f"Input: {equation}\n\n"
# Convert each word to its number representation
for i, word in enumerate(words):
formatted_result += "".join(str(letter_to_digit[char]) for char in word)
if i < len(words) - 2:
formatted_result += " + "
elif i == len(words) - 2:
formatted_result += " = "
return formatted_result
else:
return f"No solution found for: {equation}"
def process_input(equations):
results = []
for equation in equations.splitlines():
equation = equation.strip()
if equation: # Ensure it's not an empty line
result = solve_cryptarithm(equation)
results.append(result)
return "\n\n".join(results)
# Set up Gradio interface
interface = gr.Interface(
fn=process_input,
inputs=gr.Textbox(
label="Enter Cryptarithm Equations (one per line)",
placeholder="E.g., SEND + MORE = MONEY\nSEND + 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."
)
# Launch Gradio app
interface.launch()