Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

MOHAMMAD UMER

01-134202-031
BS CS 6B

def is_valid(assignment, variable, value):

# Check if the assignment is consistent with the constraints

for other_variable, other_value in assignment.items():

if other_variable != variable and other_value == value:

return False

return True

def backtrack(assignment, variables, domains):

# If the assignment is complete, return it

if len(assignment) == len(variables):

return assignment

# Select an unassigned variable

unassigned_variables = [var for var in variables if var not in assignment]

variable = unassigned_variables[0]

# Try each value from the domain for the selected variable

for value in domains[variable]:

if is_valid(assignment, variable, value):

assignment[variable] = value

result = backtrack(assignment, variables, domains)

if result is not None:

return result

del assignment[variable]

# If no assignment is possible, return None


return None

def solve_csp(variables, domains):

assignment = {}

return backtrack(assignment, variables, domains)

# Example usage:

variables = ['A', 'B', 'C']

domains = {

'A': [1, 2, 3],

'B': [4, 5, 6],

'C': [7, 8, 9]

solution = solve_csp(variables, domains)

print(solution)

You might also like