In [7]:
#! /usr/bin/python
import re
import itertools

In [8]:
def read_cities ( filename ):
    match_line = re.compile('(^[a-zA-Z]*) to ([a-zA-Z]*) = ([0-9]*)')
    table = {}
    with open(filename) as f:
        for linen in f:
            line = linen.rstrip('\n')
            if not (match_line.findall(line) == []):
                dist = (match_line.findall(line))
                table[(dist[0][0], dist[0][1])] = dist[0][2]
                table[(dist[0][1], dist[0][0])] = dist[0][2]
    return ( table )

def unique_cities ( table ):
    cities = []
    for link in table:
        if not link[0] in cities:
            cities.append(link[0])
        if not link[1] in cities:
            cities.append(link[1])
    return (cities)

def give_distance ( city_a, city_b, table ):
    return table[(city_a, city_b)]

In [9]:
#########################################################################

filename = './input'
longest = 0
shortest = 99999999

distance_table = read_cities ( filename )
all_cities = unique_cities(distance_table)

all = itertools.permutations(all_cities)
for route in all:
    distance = 0
    for i in range(0, len(route)-1):
        distance += int(give_distance(route[i], route[i+1], distance_table))
#    print (route, distance)
    if distance < shortest:
        shortest = distance
    if distance > longest:
        longest = distance

In [10]:
print("shortest route: %s" % shortest)
print("longest route: %s" % longest)


shortest route: 207
longest route: 804

In [ ]: