varlist = ('WA', 'NT', 'SA', 'Q', 'NSW', 'V', 'T' )
domain = ('red', 'green', 'blue')
neighbor = dict(WA={'NT', 'SA'}, NT= {'WA', 'SA', 'Q'},
SA={'WA', 'NT', 'Q', 'NSW', 'V'}, Q={'NT', 'SA', 'NSW'} ,
NSW={'Q', 'SA', 'V'}, V ={'SA', 'NSW'}, T={})
def some(seq):
"Return some element of seq that is true."
for e in seq:
if e: return e
return False
def assign(vals, x, d):
"Check whether assignment of d to x is feasible in vals, if so assign"
print(" "*len(vals), "check value %s for var %s" % (d, x))
for y in vals:
if x in neighbor[y] and vals[y] == d:
print(" "*len(vals), "not possible!")
return False
print(" "*len(vals), "trying out ...")
vals[x] = d
return vals
def search(vals):
"Recursively search for a satisfying assignment"
if vals is False: return False # failed earlier
nextvar = some(x for x in varlist if x not in vals)
if not nextvar:
return vals # we have found a complete assignment
else:
return some(search(assign(vals.copy(), nextvar, d))
for d in domain)
if __name__=='__main__':
print(search(dict()))