0% found this document useful (0 votes)
6 views2 pages

AI Skill 5 Printout

Uploaded by

No-one Kk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views2 pages

AI Skill 5 Printout

Uploaded by

No-one Kk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

11/18/24, 5:49 PM Untitled11.

ipynb - Colab

Constraint Satisfaction Problem

import itertools

# Function to extract all unique letters from the problem


def extract_letters(problem):
letters = set()
for char in problem:
if char.isalpha():
letters.add(char)
return letters

# Function to substitute the letter mappings into the problem


def substitute(problem, mapping):
result = problem
for letter, digit in mapping.items():
result = result.replace(letter, str(digit))
return result

# Function to check if a given solution satisfies the equation


def check_solution(problem, mapping):
substituted_problem = substitute(problem, mapping)

# Split the equation into parts (Left-hand side and right-hand side)
lhs, rhs = substituted_problem.split('=')
lhs_sum = sum(map(int, lhs.split('+')))
rhs_value = int(rhs)

return lhs_sum == rhs_value

# Function to solve crypto-arithmetic problem


def solve_crypto_arithmetic(problem):
letters = extract_letters(problem)

if len(letters) > 10:


print("Too many unique letters to map to digits.")
return

# Generate all possible permutations of digits for the letters


digits = range(10)
for perm in itertools.permutations(digits, len(letters)):
mapping = dict(zip(letters, perm))

# Ensure that no leading zeros are used for the letters at the start
words = problem.split(' ')
leading_letters = [word[0] for word in words if word[0].isalpha()]
if any(mapping[letter] == 0 for letter in leading_letters):
https://colab.research.google.com/drive/1bZjdMYXiYFoal87uIXW936fELJOThsuB#scrollTo=hsx… 1/3
11/18/24, 5:49 PM Untitled11.ipynb - Colab
continue

if check_solution(problem, mapping):
return mapping

return None

# Main function to input problem and solve it


def main():
print("Enter a crypto-arithmetic problem (e.g., 'SEND + MORE = MONEY')"
problem = input().strip()

solution = solve_crypto_arithmetic(problem)

if solution:
print("Solution found:")
for letter, digit in solution.items():
print(f"{letter} = {digit}")
else:
print("No solution found.")

if __name__ == "__main__":
main()

Enter a crypto-arithmetic problem (e.g., 'SEND + MORE = MONEY')


CROSS + ROADS = DANGER
Solution found:
S = 3
R = 6
N = 8
G = 7
E = 4
O = 2
C = 9
A = 5
D = 1

https://colab.research.google.com/drive/1bZjdMYXiYFoal87uIXW936fELJOThsuB#scrollTo=hsx… 2/3

You might also like