Skip to content

Commit 7c58ce6

Browse files
author
Laurent Perron
committed
fix examples to work with python3, linear_solver is not yet working; tested with python 3.5
1 parent de9a5b6 commit 7c58ce6

5 files changed

Lines changed: 42 additions & 42 deletions

File tree

examples/python/integer_programming.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -56,8 +56,8 @@ def RunIntegerExampleCppStyleAPI(optimization_problem_type):
5656

5757
def SolveAndPrint(solver, variable_list):
5858
"""Solve the problem and print the solution."""
59-
print 'Number of variables = %d' % solver.NumVariables()
60-
print 'Number of constraints = %d' % solver.NumConstraints()
59+
print('Number of variables = %d' % solver.NumVariables())
60+
print('Number of constraints = %d' % solver.NumConstraints())
6161

6262
result_status = solver.Solve()
6363

@@ -68,17 +68,17 @@ def SolveAndPrint(solver, variable_list):
6868
# GLOP_LINEAR_PROGRAMMING, verifying the solution is highly recommended!).
6969
assert solver.VerifySolution(1e-7, True)
7070

71-
print 'Problem solved in %f milliseconds' % solver.wall_time()
71+
print('Problem solved in %f milliseconds' % solver.wall_time())
7272

7373
# The objective value of the solution.
74-
print 'Optimal objective value = %f' % solver.Objective().Value()
74+
print('Optimal objective value = %f' % solver.Objective().Value())
7575

7676
# The value of each variable in the solution.
7777
for variable in variable_list:
78-
print '%s = %f' % (variable.name(), variable.solution_value())
78+
print('%s = %f' % (variable.name(), variable.solution_value()))
7979

80-
print 'Advanced usage:'
81-
print 'Problem solved in %d branch-and-bound nodes' % solver.nodes()
80+
print('Advanced usage:')
81+
print('Problem solved in %d branch-and-bound nodes' % solver.nodes())
8282

8383

8484
def Announce(solver, api_type):

examples/python/knapsack.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ def main():
4141
solver.Init(profits, weights, capacities)
4242
computed_profit = solver.Solve()
4343

44-
print 'optimal profit = ' + str(computed_profit) + '/' + str(optimal_profit)
44+
print('optimal profit = ' + str(computed_profit) + '/' + str(optimal_profit))
4545

4646

4747
if __name__ == '__main__':

examples/python/linear_programming.py

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ def RunLinearExampleNaturalLanguageAPI(optimization_problem_type):
3636

3737
SolveAndPrint(solver, [x1, x2, x3], [c0, c1, c2])
3838
# Print a linear expression's solution value.
39-
print 'Sum of vars: %s = %s' % (sum_of_vars, sum_of_vars.solution_value())
39+
print('Sum of vars: %s = %s' % (sum_of_vars, sum_of_vars.solution_value()))
4040

4141

4242
def RunLinearExampleCppStyleAPI(optimization_problem_type):
@@ -79,8 +79,8 @@ def RunLinearExampleCppStyleAPI(optimization_problem_type):
7979

8080
def SolveAndPrint(solver, variable_list, constraint_list):
8181
"""Solve the problem and print the solution."""
82-
print 'Number of variables = %d' % solver.NumVariables()
83-
print 'Number of constraints = %d' % solver.NumConstraints()
82+
print('Number of variables = %d' % solver.NumVariables())
83+
print('Number of constraints = %d' % solver.NumConstraints())
8484

8585
result_status = solver.Solve()
8686

@@ -91,24 +91,24 @@ def SolveAndPrint(solver, variable_list, constraint_list):
9191
# GLOP_LINEAR_PROGRAMMING, verifying the solution is highly recommended!).
9292
assert solver.VerifySolution(1e-7, True)
9393

94-
print 'Problem solved in %f milliseconds' % solver.wall_time()
94+
print('Problem solved in %f milliseconds' % solver.wall_time())
9595

9696
# The objective value of the solution.
97-
print 'Optimal objective value = %f' % solver.Objective().Value()
97+
print('Optimal objective value = %f' % solver.Objective().Value())
9898

9999
# The value of each variable in the solution.
100100
for variable in variable_list:
101-
print '%s = %f' % (variable.name(), variable.solution_value())
101+
print('%s = %f' % (variable.name(), variable.solution_value()))
102102

103-
print 'Advanced usage:'
104-
print 'Problem solved in %d iterations' % solver.iterations()
103+
print('Advanced usage:')
104+
print('Problem solved in %d iterations' % solver.iterations())
105105
for variable in variable_list:
106-
print '%s: reduced cost = %f' % (variable.name(), variable.reduced_cost())
106+
print('%s: reduced cost = %f' % (variable.name(), variable.reduced_cost()))
107107
activities = solver.ComputeConstraintActivities()
108108
for i, constraint in enumerate(constraint_list):
109-
print ('constraint %d: dual value = %f\n'
110-
' activity = %f' %
111-
(i, constraint.dual_value(), activities[constraint.index()]))
109+
print('constraint %d: dual value = %f\n'
110+
' activity = %f' %
111+
(i, constraint.dual_value(), activities[constraint.index()]))
112112

113113

114114
def main():
@@ -121,10 +121,10 @@ def main():
121121
# Skip problem types that aren't supported by the current binary.
122122
if not pywraplp.Solver.SupportsProblemType(problem_type):
123123
continue
124-
print '\n------ Linear programming example with %s ------' % name
125-
print '\n*** Natural language API ***'
124+
print('\n------ Linear programming example with %s ------' % name)
125+
print('\n*** Natural language API ***')
126126
RunLinearExampleNaturalLanguageAPI(problem_type)
127-
print '\n*** C++ style API ***'
127+
print('\n*** C++ style API ***')
128128
RunLinearExampleCppStyleAPI(problem_type)
129129

130130

examples/python/pyflow_example.py

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020

2121
def MaxFlow():
2222
"""MaxFlow simple interface example."""
23-
print 'MaxFlow on a simple network.'
23+
print('MaxFlow on a simple network.')
2424
tails = [0, 0, 0, 0, 1, 2, 3, 3, 4]
2525
heads = [1, 2, 3, 4, 3, 4, 4, 5, 5]
2626
capacities = [5, 8, 5, 3, 4, 5, 6, 6, 4]
@@ -29,17 +29,17 @@ def MaxFlow():
2929
for i in range(0, len(tails)):
3030
max_flow.AddArcWithCapacity(tails[i], heads[i], capacities[i])
3131
if max_flow.Solve(0, 5) == max_flow.OPTIMAL:
32-
print 'Total flow', max_flow.OptimalFlow(), '/', expected_total_flow
32+
print('Total flow', max_flow.OptimalFlow(), '/', expected_total_flow)
3333
for i in range(max_flow.NumArcs()):
34-
print 'From source %d to target %d: %d / %d' % (
34+
print('From source %d to target %d: %d / %d' % (
3535
max_flow.Tail(i),
3636
max_flow.Head(i),
3737
max_flow.Flow(i),
38-
max_flow.Capacity(i))
39-
print 'Source side min-cut:', max_flow.GetSourceSideMinCut()
40-
print 'Sink side min-cut:', max_flow.GetSinkSideMinCut()
38+
max_flow.Capacity(i)))
39+
print('Source side min-cut:', max_flow.GetSourceSideMinCut())
40+
print('Sink side min-cut:', max_flow.GetSinkSideMinCut())
4141
else:
42-
print 'There was an issue with the max flow input.'
42+
print('There was an issue with the max flow input.')
4343

4444

4545
def MinCostFlow():
@@ -48,7 +48,7 @@ def MinCostFlow():
4848
Note that this example is actually a linear sum assignment example and will
4949
be more efficiently solved with the pywrapgraph.LinearSumAssignement class.
5050
"""
51-
print 'MinCostFlow on 4x4 matrix.'
51+
print('MinCostFlow on 4x4 matrix.')
5252
num_sources = 4
5353
num_targets = 4
5454
costs = [[90, 75, 75, 80],
@@ -66,15 +66,15 @@ def MinCostFlow():
6666
min_cost_flow.SetNodeSupply(num_sources + node, -1)
6767
status = min_cost_flow.Solve()
6868
if status == min_cost_flow.OPTIMAL:
69-
print 'Total flow', min_cost_flow.OptimalCost(), '/', expected_cost
69+
print('Total flow', min_cost_flow.OptimalCost(), '/', expected_cost)
7070
for i in range(0, min_cost_flow.NumArcs()):
7171
if min_cost_flow.Flow(i) > 0:
72-
print 'From source %d to target %d: cost %d' % (
72+
print('From source %d to target %d: cost %d' % (
7373
min_cost_flow.Tail(i),
7474
min_cost_flow.Head(i) - num_sources,
75-
min_cost_flow.UnitCost(i))
75+
min_cost_flow.UnitCost(i)))
7676
else:
77-
print 'There was an issue with the min cost flow input.'
77+
print('There was an issue with the min cost flow input.')
7878

7979

8080
def main():

examples/python/tsp.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -60,9 +60,9 @@ def __init__(self, size, seed):
6060
rand.seed(seed)
6161
distance_max = 100
6262
self.matrix = {}
63-
for from_node in xrange(size):
63+
for from_node in range(size):
6464
self.matrix[from_node] = {}
65-
for to_node in xrange(size):
65+
for to_node in range(size):
6666
if from_node == to_node:
6767
self.matrix[from_node][to_node] = 0
6868
else:
@@ -111,15 +111,15 @@ def main(args):
111111
from_node = rand.randrange(args.tsp_size - 1)
112112
to_node = rand.randrange(args.tsp_size - 1) + 1
113113
if routing.NextVar(from_node).Contains(to_node):
114-
print 'Forbidding connection ' + str(from_node) + ' -> ' + str(to_node)
114+
print('Forbidding connection ' + str(from_node) + ' -> ' + str(to_node))
115115
routing.NextVar(from_node).RemoveValue(to_node)
116116
forbidden_connections += 1
117117

118118
# Solve, returns a solution if any.
119119
assignment = routing.SolveWithParameters(parameters, None)
120120
if assignment:
121121
# Solution cost.
122-
print assignment.ObjectiveValue()
122+
print(assignment.ObjectiveValue())
123123
# Inspect solution.
124124
# Only one route here; otherwise iterate from 0 to routing.vehicles() - 1
125125
route_number = 0
@@ -129,11 +129,11 @@ def main(args):
129129
route += str(node) + ' -> '
130130
node = assignment.Value(routing.NextVar(node))
131131
route += '0'
132-
print route
132+
print(route)
133133
else:
134-
print 'No solution found.'
134+
print('No solution found.')
135135
else:
136-
print 'Specify an instance greater than 0.'
136+
print('Specify an instance greater than 0.')
137137

138138
if __name__ == '__main__':
139139
main(parser.parse_args())

0 commit comments

Comments
 (0)