第9天代码的出现

时间:2015-12-14 06:09:39

标签: python shortest-path brute-force

我试图抓住我的adventofcode.com

解决方案(目前在第9天)但事实证明这一天有点棘手。

我已经把其他人弄得很好(这需要一段时间,但最终我解决了所有问题)。

然而,这个我无法绕过头脑。我之前从未尝试过这样的问题,而且在制作城市的每一个排列方面都遇到了麻烦。

一旦我这样做,我可以 min()找到最短的路径,但我的解决方案被证明无效(答案仍然太高)。

目前的解决方案:

#!/usr/bin/env python2.7

destinations = open('day9.txt', 'r').read().split('\n')
distances = []

for dest in destinations:
    dest = dest.split()
    distances.append(int(dest[-1]))

    for sub_dest in destinations:
        sub_dest = sub_dest.split()

        if dest == sub_dest:
            continue

        distances[-1] += int(sub_dest[-1])

print min(set(distances))

和day9.txt:

Tristram to AlphaCentauri = 34
Tristram to Snowdin = 100
Tristram to Tambi = 63
Tristram to Faerun = 108
Tristram to Norrath = 111
Tristram to Straylight = 89
Tristram to Arbre = 132
AlphaCentauri to Snowdin = 4
AlphaCentauri to Tambi = 79
AlphaCentauri to Faerun = 44
AlphaCentauri to Norrath = 147
AlphaCentauri to Straylight = 133
AlphaCentauri to Arbre = 74
Snowdin to Tambi = 105
Snowdin to Faerun = 95
Snowdin to Norrath = 48
Snowdin to Straylight = 88
Snowdin to Arbre = 7
Tambi to Faerun = 68
Tambi to Norrath = 134
Tambi to Straylight = 107
Tambi to Arbre = 40
Faerun to Norrath = 11
Faerun to Straylight = 66
Faerun to Arbre = 144
Norrath to Straylight = 115
Norrath to Arbre = 135
Straylight to Arbre = 127

1 个答案:

答案 0 :(得分:1)

要列出城市(或任何列表)的所有排列,您可以使用itertools.permutations:

>>> from itertools import permutations
>>> for p in permutations(["London", "Belfast", "Dublin"]):
...   print p
... 
('London', 'Belfast', 'Dublin')
('London', 'Dublin', 'Belfast')
('Belfast', 'London', 'Dublin')
('Belfast', 'Dublin', 'London')
('Dublin', 'London', 'Belfast')
('Dublin', 'Belfast', 'London')

如果你想自己实现permutations功能,只需要考虑通过选择所有可能城市中的第一个城市来获得每个排列,然后加入剩余城市的所有可能排列......

可能的解决方案:

data = {}  # (city_from, city_to) -> distance                                                                                                 
for line in open("day9.txt"):
    start, to, end, equals, distance = line.split()
    assert to == "to"
    assert equals == "="
    data[(start, end)] = data[(end, start)] = int(distance)

cities = list(set([key[0] for key in data]))

def permutations(lst):
    if not lst:
        yield []
    for i, first in enumerate(lst):
        for rest in permutations(lst[:i]+lst[i+1:]):
            yield [first] + rest

minimal_cost = float("inf")
best_path = None
for perm in permutations(cities):
    cost = sum([data[couple] for couple in zip(perm[:-1], perm[1:])])
    if cost < minimal_cost:
        minimal_cost = cost
        best_path = perm

print best_path
print minimal_cost