Skip to content

Instantly share code, notes, and snippets.

@shintakezou
Last active September 26, 2015 10:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shintakezou/8fdcdf65e15cd7f1ca9a to your computer and use it in GitHub Desktop.
Save shintakezou/8fdcdf65e15cd7f1ca9a to your computer and use it in GitHub Desktop.
Solve Susi's puzzle n. 927 using logilab.constraint
#! /usr/bin/python
#
# see https://gist.github.com/shintakezou/666a96e63b0c01be2f78#file-susi927-py
# The problem is the same, but here we use logilab.constraint
# https://www.logilab.org/project/logilab-constraint
# and of course we take into account the fact that prices are integer
# positive numbers.
#
from logilab.constraint import *
bottle_no = ["a", "b", "c"]
prices = ["R", "S", "B"]
domains = {}
# we have at least one bottle per type, and since a + b + c = 7,
# then none of a, b or c can be greater than 5
for v in bottle_no:
domains[v] = fd.FiniteDomain(range(1, 5+1))
# we can make this domain a little bit smaller; e.g.
# if, say, a=1, b=1, c=5, and R=1, S (B) would be 113, and this is
# the higher price for a bottle, if this eq must hold.
# No reason to narrow the domain this way, hence I keep it
# straightforward.
for v in prices:
domains[v] = fd.FiniteDomain(range(1, 119+1))
cons = []
cons.append(fd.make_expression(("a","b","c"), "a + b + c == 7"))
cons.append(fd.make_expression(("R", "B"), "R == 3*B"))
cons.append(fd.make_expression(("R", "S"), "7*R == 3*S"))
cons.append(fd.make_expression(("a","b","c","S","B","R"), "a*S+b*B+c*R==119"))
r = Repository(bottle_no + prices, domains, cons)
s = Solver().solve(r)
for sol in s: # we expect one solution, but let's loop anyway
print "price of sparkling wine = %d"%(sol["S"]) # -> 49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment