This repository contains a simple Python program to solve cryptarithmetic puzzles. Cryptarithmetic puzzles involve mathematical equations where letters replace digits. The task is to find the unique digit for each letter such that the equation holds true.
- Supports custom cryptarithmetic puzzles.
- Evaluates all possible digit combinations.
- Skips invalid mappings (e.g., leading zeros).
- Efficiently finds and displays the correct solution if it exists.
AB + AB == BCC
Sample Solution:
61 + 61 = 122
Clone the repository:
git clone https://github.com/sibeux/cryptarithmetic-python.git
Navigate to the project directory:
cd cryptarithmetic-pythonRun the program:
cryptarithm.py
Enter your puzzle when prompted, e.g.,
AB + AB = BCC.
- Python 3.6 or higher
- Extracts unique letters from the puzzle.
- Generates all possible digit permutations.
- Evaluates each permutation to find the correct solution.
fromitertoolsimportproductinput1=str(input("Enter the first letter: "))
input2=str(input("Enter the second letter: "))
print("----------------------------- +")
result=str(input("Enter the result: "))
arrayInput1=list(input1)
arrayInput2=list(input2)
arrayResult=list(result)
permInput1=product(
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], repeat=arrayInput1.__len__())
permInput2=product(
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], repeat=arrayInput2.__len__())
combInput1= []
combInput2= []
foriinlist(permInput1):
combInput1.append(i)
foriinlist(permInput2):
combInput2.append(i)
totalPenyelesaian=0foriincombInput1:
forjincombInput2:
bilA=int("".join(map(str, i)))
bilB=int("".join(map(str, j)))
hasil=bilA+bilBiflen(str(hasil)) ==len(arrayResult):
numbInput1=list(i)
numbInput2=list(j)
numbResult=list(str(hasil))
numbInput1=list(map(str, numbInput1))
numbInput2=list(map(str, numbInput2))
allList=arrayInput1+arrayInput2+arrayResultallListNumb=numbInput1+numbInput2+numbResultsetAllList=set(allList)
setAllListNumb=set(allListNumb)
if (len(setAllList) ==len(setAllListNumb)):
count=0forindexSetAllListinrange (0, len(setAllList)):
listSetAllList=list(setAllList)
indexValue= [ifori, xinenumerate(
allList) ifx==listSetAllList[indexSetAllList]]
numbByIndexValue= []
fori_indexValueinindexValue:
numbByIndexValue.append(allListNumb[i_indexValue])
setNumbByIndexValue=set(numbByIndexValue)
iflen(setNumbByIndexValue) ==1:
count+=1else:
breakifcount==len(setAllList):
totalPenyelesaian+=1print(f"{bilA} + {bilB} = {hasil}")
print(f"Total Penyelesaian: {totalPenyelesaian}")