Given a cryptarithm puzzle using four letters, such as ['a','b','cd'], and a list of the four solution digits, such as [1,4,6,8], figure out the mapping of digits to letters that solves the cryptarithm. There will be two addends, so the length of the puzzle list is 3. The solution should be expressed as a
string; for example, '6+8=14
This is the algorithm to follow
Create a list of the four distinct letters used in the puzzle. Example: ['a','b','c','d']
For each number in the solution digit list,
Let the first letter from the letter list be associated with that number
For each remaining number in the solution digit list,
Let the second letter in the letter list be associated with that number
For each remaining number in the solution digit list,
Let the third letter be associated with this number
Let the fourth letter be associated with the other number.
Check to see if these number associations solve the puzzle or not
If so, return the solution in the required format
If no solutions are found, return a helpful message.
Type the possible code.
def solve(puzzle,digitList):
.
Please find the below code for the above mentioned assignment, I hope this will help you if yes, give me a thumps up!
def solve(puzzle, digitList):
distinct_letters = []
letter_association = {}
solution = []
for i in puzzle:
for x in i:
if x not in distinct_letters:
distinct_letters.append(x)
letter_association[x] = ""
for i in digitList:
letter_association[distinct_letters[0]] = digitList[digitList.index(i)]
for j in (list(list(set(digitList) - {i}))):
letter_association[distinct_letters[1]] = digitList[digitList.index(j)]
for k in (list(list(set(digitList) - {i, j}))):
letter_association[distinct_letters[2]] = digitList[digitList.index(k)]
for l in (list(list(set(digitList) - {i, j, k}))):
letter_association[distinct_letters[3]] = digitList[digitList.index(l)]
expr_1 = puzzle[0]
expr_2 = puzzle[1]
expr_3 = puzzle[2]
int_1 = ""
int_2 = ""
int_3 = ""
for z in expr_1:
int_1 += str(letter_association[z])
int_1 = int(int_1)
for z in expr_2:
int_2 += str(letter_association[z])
int_2 = int(int_2)
for z in expr_3:
int_3 += str(letter_association[z])
int_3 = int(int_3)
if int_1 + int_2 == int_3:
solution.append("{}+{}={}".format(int_1, int_2, int_3))
if len(solution) == 0:
print("No Solutions found for the puzzle!!")
return [-1]
return solution
def testCase(testNumber, puzzle, digits, expectedList):
actualResult = solve(puzzle, digits)
if sorted(actualResult) == sorted(expectedList):
print("Test ", testNumber, " passed.")
else:
print("Test ", testNumber, " failed. Expected one of: {} Actual: {}".format(expectedList, actualResult))
def test():
testCase(1, ['a', 'b', 'cd'], [1, 4, 6, 8], ['6+8=14', '8+6=14'])
testCase(2, ['q', 'r', 'st'], [5, 2, 1, 7], ['5+7=12', '7+5=12'])
testCase(3, ['xyz', 'zx', 'xzw'], [4, 7, 0, 3], ['403+34=437', '304+43=347'])
test()
Get Answers For Free
Most questions answered within 1 hours.