【问题标题】:Day 9 Advent of Code第 9 天 代码出现
【发布时间】:2016-03-19 13:32:05
【问题描述】:

我正在尝试关注我的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

【问题讨论】:

  • 问题陈述是?
  • err sorry... 本来是想把它放在最后,但我没想到。已编辑

标签: python shortest-path brute-force


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-31
    • 2011-06-02
    • 2018-03-04
    • 1970-01-01
    相关资源
    最近更新 更多