PySCIPOpt
Python Interface to the SCIP Optimization Suite
even.py
Go to the documentation of this file.
1
##@file finished/even.py
2
#@brief model to decide whether argument is even or odd
3
4
5
6
################################################################################
7
#
8
# EVEN OR ODD?
9
#
10
# If a positional argument is given:
11
# prints if the argument is even/odd/neither
12
# else:
13
# prints if a value is even/odd/neither per each value in a example list
14
#
15
# This example is made for newcomers and motivated by:
16
# - modulus is unsupported for pyscipopt.scip.Variable and int
17
# - variables are non-integer by default
18
# Based on this:
19
# https://github.com/SCIP-Interfaces/PySCIPOpt/issues/172#issuecomment-394644046
20
#
21
################################################################################
22
23
from
pyscipopt
import
Model
24
25
verbose =
False
26
sdic = {0:
"even"
,1:
"odd"
}
27
28
def
parity(number):
29
try
:
30
assert
number == int(round(number))
31
m = Model()
32
m.hideOutput()
33
34
### variables are non-negative by default since 0 is the default lb.
35
### To allow for negative values, give None as lower bound
36
### (None means -infinity as lower bound and +infinity as upper bound)
37
x = m.addVar(
"x"
, vtype=
"I"
, lb=
None
, ub=
None
)
#ub=None is default
38
n = m.addVar(
"n"
, vtype=
"I"
, lb=
None
)
39
s = m.addVar(
"s"
, vtype=
"B"
)
40
41
### CAVEAT: if number is negative, x's lb must be None
42
### if x is set by default as non-negative and number is negative:
43
### there is no feasible solution (trivial) but the program
44
### does not highlight which constraints conflict.
45
m.addCons(x==number)
46
47
m.addCons(s == x-2*n)
48
m.setObjective(s)
49
m.optimize()
50
51
assert
m.getStatus() ==
"optimal"
52
if
verbose:
53
for
v
in
m.getVars():
54
print(
"%s %d"
% (v,m.getVal(v)))
55
print(
"%d%%2 == %d?"
% (m.getVal(x), m.getVal(s)))
56
print(m.getVal(s) == m.getVal(x)%2)
57
58
xval = m.getVal(x)
59
sval = m.getVal(s)
60
sstr = sdic[sval]
61
print(
"%d is %s"
% (xval, sstr))
62
except
(AssertionError, TypeError):
63
print(
"%s is neither even nor odd!"
% number.__repr__())
64
65
if
__name__ ==
"__main__"
:
66
import
sys
67
from
ast
import
literal_eval
as
leval
68
example_values = [0, 1, 1.5,
"hallo welt"
, 20, 25, -101, -15., -10, -int(2**31), int(2**31-1), int(2**63)-1]
69
try
:
70
try
:
71
n = leval(sys.argv[1])
72
except
ValueError:
73
n = sys.argv[1]
74
parity(n)
75
except
IndexError:
76
for
n
in
example_values:
77
parity(n)
examples
finished
even.py
Generated by
1.8.11