Department numbers: Difference between revisions
Content added Content deleted
(→{{header|Minimal BASIC}}: Corrected. Minimal BASIC does not have the operators OR, AND, NOT.) |
(→{{header|Python}}: Add python-constraint solution) |
||
Line 3,816: | Line 3,816: | ||
Police: 6 Sanitation: 4 Fire: 2 |
Police: 6 Sanitation: 4 Fire: 2 |
||
</pre> |
</pre> |
||
===Using a constraint solver=== |
|||
A problem this trivial is amenable to brute-force solutions such as the above, but it is a good example of the type of problem for which a constraint solver can be useful. This is how one could solve it using the `python-constraint` library: |
|||
{{libheader|python-constraint}} |
|||
<syntaxhighlight lang="python">import constraint |
|||
depts = [ 'police', 'sanitation', 'fire' ] |
|||
p = constraint.Problem() |
|||
for var in depts: |
|||
p.addVariable(var, range(1,8)) |
|||
p.addConstraint(constraint.AllDifferentConstraint()) |
|||
p.addConstraint(lambda *vars: sum(vars)==12, depts) |
|||
p.addConstraint(lambda p: p%2==0, ['police']) |
|||
for s in p.getSolutions(): |
|||
print(s)</syntaxhighlight> |
|||
{{Out}} |
|||
<pre>{'police': 6, 'fire': 5, 'sanitation': 1} |
|||
{'police': 6, 'fire': 4, 'sanitation': 2} |
|||
{'police': 6, 'fire': 2, 'sanitation': 4} |
|||
{'police': 6, 'fire': 1, 'sanitation': 5} |
|||
{'police': 4, 'fire': 6, 'sanitation': 2} |
|||
{'police': 4, 'fire': 7, 'sanitation': 1} |
|||
{'police': 4, 'fire': 5, 'sanitation': 3} |
|||
{'police': 4, 'fire': 3, 'sanitation': 5} |
|||
{'police': 4, 'fire': 2, 'sanitation': 6} |
|||
{'police': 4, 'fire': 1, 'sanitation': 7} |
|||
{'police': 2, 'fire': 4, 'sanitation': 6} |
|||
{'police': 2, 'fire': 6, 'sanitation': 4} |
|||
{'police': 2, 'fire': 7, 'sanitation': 3} |
|||
{'police': 2, 'fire': 3, 'sanitation': 7}</pre> |
|||
=={{header|Quackery}}== |
=={{header|Quackery}}== |