SHARE
TWEET

Untitled

a guest Sep 15th, 2019 91 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import itertools, copy
  2. from csp import *
  3.  
  4. def generate_and_test(csp):
  5.     names, domains = zip(*csp.var_domains.items())
  6.     for values in itertools.product(*domains):
  7.         assignment = {x: v for x, v in zip(names, values)}
  8.         if all(satisfies(assignment, constraint) for constraint in csp.constraints):
  9.             yield assignment
  10.  
  11. def arc_consistent(csp):
  12.     csp = copy.deepcopy(csp)
  13.     tda = {(x, c) for c in csp.constraints for x in scope(c)}
  14.     while tda:
  15.         x, c = tda.pop()
  16.         ys = list(scope(c) - {x})
  17.         new_domain = set()
  18.         for xval in csp.var_domains[x]:
  19.             assignment = {x: xval}
  20.             for yvals in itertools.product(*[csp.var_domains[y] for y in ys]):
  21.                 assignment.update({y: yval for y, yval in zip(ys, yvals)})
  22.                 if satisfies(assignment, c):
  23.                     new_domain.add(xval)
  24.                     break
  25.         if csp.var_domains[x] != new_domain:
  26.             csp.var_domains[x] = new_domain
  27.             for cprime in set(csp.constraints) - {c}:
  28.                 if x in scope(c):
  29.                     for z in scope(cprime):
  30.                         if x != z:
  31.                             tda.add((z, cprime))
  32.     return csp
  33.  
  34. cryptic_puzzle = CSP(
  35.     var_domains={x: set(range(0 if x != 'f' else 1, 10)) for x in 'twofur'
  36.         },
  37.     constraints={
  38.         lambda t, w, o, f, u, r: len(set([t, w, o, f, u, r])) == 6,
  39.         lambda o, r: (o + o) % 10 == r,
  40.         lambda o, w, u: ((0 if o < 5 else 1) + w + w) % 10 == u,
  41.         lambda w, t, o: ((0 if w < 5 else 1) + t + t) % 10 == o,
  42.         lambda t: t + t >= 10,
  43.         lambda f: f == 1,
  44.         })
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top