aboutsummaryrefslogtreecommitdiff
path: root/challenge-121/abigail/python/ch-2.py
diff options
context:
space:
mode:
authorLuis Mochan <mochan@fis.unam.mx>2021-07-19 14:26:28 -0500
committerLuis Mochan <mochan@fis.unam.mx>2021-07-19 14:26:28 -0500
commite542ee52b8f6be5d340550000cbe98f4b2aefb1e (patch)
treef419b7bb3501203a1d2b637eeb61df2eba87768d /challenge-121/abigail/python/ch-2.py
parent51feed7f6f1ba280658615d36ee2f7ccf77b5000 (diff)
parent675c4ed9a3b441729b9558c051638027242ba77a (diff)
downloadperlweeklychallenge-club-e542ee52b8f6be5d340550000cbe98f4b2aefb1e.tar.gz
perlweeklychallenge-club-e542ee52b8f6be5d340550000cbe98f4b2aefb1e.tar.bz2
perlweeklychallenge-club-e542ee52b8f6be5d340550000cbe98f4b2aefb1e.zip
Merge branch 'master' of github.com:manwar/perlweeklychallenge-club into challenges
Diffstat (limited to 'challenge-121/abigail/python/ch-2.py')
-rw-r--r--challenge-121/abigail/python/ch-2.py40
1 files changed, 40 insertions, 0 deletions
diff --git a/challenge-121/abigail/python/ch-2.py b/challenge-121/abigail/python/ch-2.py
new file mode 100644
index 0000000000..c01e43bf43
--- /dev/null
+++ b/challenge-121/abigail/python/ch-2.py
@@ -0,0 +1,40 @@
+#!/opt/local/bin/python
+
+#
+# See ../README.md
+#
+
+#
+# Run as: python ch-2.py < input-file
+#
+
+import fileinput
+
+def shortest_path (matrix, start, to, exclude):
+ if 1 + len (exclude . keys ()) == len (matrix):
+ return matrix [start] [to], [to]
+
+ shortest = 9999999999999999999
+ sh_path = []
+ new_exclude = exclude . copy ()
+ new_exclude [start] = 1
+
+ for next in range (len (matrix)):
+ if next == start or next == to or next in exclude:
+ continue
+ length, path = shortest_path (matrix, next, to, new_exclude)
+ if shortest > length + matrix [start] [next]:
+ shortest = length + matrix [start] [next]
+ sh_path = [next] + path
+
+ return shortest, sh_path
+
+
+matrix = []
+for line in fileinput . input ():
+ matrix . append (list (map (lambda x: int (x), line . split (" "))))
+
+length, path = shortest_path (matrix, 0, 0, {})
+
+print (length)
+print (0, " " . join (map (lambda x: str (x), path)))