Skip to content

Commit bb3ac39

Browse files
committed
Create CSV output for python iterated local search.
1 parent a186f02 commit bb3ac39

File tree

1 file changed

+16
-4
lines changed

1 file changed

+16
-4
lines changed

python/stochastic/iterated_local_search.py

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
import math
66
import random
7+
import sys
78

89
"""
910
2.5
@@ -93,7 +94,7 @@ def perturbation(cities, best):
9394
candidate["cost"] = path_cost(candidate["vector"], cities)
9495
return candidate
9596

96-
def search(cities, max_iterations, max_no_improv):
97+
def search(cities, max_iterations, max_no_improv, output_format="human"):
9798
best = {}
9899
best["vector"] = random_permutation(cities)
99100
best["cost"] = path_cost(best["vector"], cities)
@@ -106,7 +107,10 @@ def search(cities, max_iterations, max_no_improv):
106107
if candidate["cost"] < best["cost"]:
107108
best = candidate
108109

109-
print("Iteration #" + str(i) + " best = " + str(best["cost"]))
110+
if output_format == "csv":
111+
print("%s,%s" % (i, best["cost"]))
112+
else:
113+
print("Iteration #" + str(i) + " best = " + str(best["cost"]))
110114

111115
return best
112116

@@ -116,7 +120,15 @@ def search(cities, max_iterations, max_no_improv):
116120
# Algorithm configuration
117121
max_iterations = 100
118122
max_no_improv = 50
123+
output_format = "human"
124+
125+
if len(sys.argv) >= 2:
126+
output_format = sys.argv[1]
119127

120128
# Execute the algorithm
121-
best = search(berlin52, max_iterations, max_no_improv)
122-
print("Done. Best solution: c = " + str(best["cost"]) +", v = " + str(best["vector"]))
129+
best = search(berlin52, max_iterations, max_no_improv, output_format)
130+
131+
if output_format == "csv":
132+
print("%s,%s" % (best["cost"], ",".join([str(i) for i in best["vector"]])))
133+
else:
134+
print("Done. Best solution: c = " + str(best["cost"]) +", v = " + str(best["vector"]))

0 commit comments

Comments
 (0)