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 not False:
nextvar = some(x for x in varlist if x not in vals)
if not nextvar:
yield vals # we have found a complete assignment
else:
for d in domain:
for result in search(assign(vals.copy(), nextvar, d)):
yield result
if __name__=='__main__':
for result in search(dict()):
print(result)
input("\nnext solution?")