走廊问题 - python 有办法解决吗?

hallway problem - is there a way to solve in python?

hallway problem picture

有一些房间和走廊。其中两个房间与走廊相连。这些房间中的每一个都有一个房间与之相连。那些与走廊没有连接。你看 this 就容易多了。 无论如何。

我有这个:

#
def possible_path(lst):
    d = {
        1 : [2],
        2 : [1,"H"],
        "H" : [2,4],
        4 : ["H", 3],
        3 : [4]
    }
    for i in range(len(lst)):
        ele1, ele2 = lst[i-1], lst[i]
        if not ele2 in d[ele1]:
            return False
    return True
#

但它给了我错误的答案。 (possible_path([1, 2, "H", 4, 3]) 应该输出 True,但我的代码输出 false。)

FAILED: False should equal True
ERROR: Traceback:
   in <module>
  File "./frameworks/python/cw-2.py", line 28, in assert_equals
    expect(actual == expected, message, allow_raise)
  File "./frameworks/python/cw-2.py", line 18, in expect
    raise AssertException(message)
cw-2.AssertException: False should equal True

通过打印 ele1 和 ele2,它在应该 (1,2) 时给出 (3,1)。 下面是所有的测试,有待进一步验证。

(possible_path([1, 2, "H", 4, 3]), True)
(possible_path(["H", 1, 2]), False)
(possible_path([4, 3, 4, "H", 4, "H"]), True)
(possible_path(["H"]), True)
(possible_path([1]), True)
(possible_path([1, 2, 1]), True)
(possible_path(["H", 2, 1, "H", 2]), False)
(possible_path([3, "H", 2, 1]), False)
(possible_path(["H", 2, 3, "H"]), False)
(possible_path([1, 3, 4]), False)

您只需要将range(len(lst))更改为range(1, len(lst))。这是因为当 i == 0 时,if 条件变为 if not lst[0] in d[-1],这是您不想要的。

def possible_path(lst):
    d = {1: [2], 2: [1,"H"], "H": [2,4], 4: ["H",3], 3: [4]}
    for i in range(1, len(lst)):
        ele1, ele2 = lst[i-1], lst[i]
        if not ele2 in d[ele1]:
            return False
    return True

def verify(a, b):
    print(a == b)

verify(possible_path([1, 2, "H", 4, 3]), True)
verify(possible_path(["H", 1, 2]), False)
verify(possible_path([4, 3, 4, "H", 4, "H"]), True)
verify(possible_path(["H"]), True)
verify(possible_path([1]), True)
verify(possible_path([1, 2, 1]), True)
verify(possible_path(["H", 2, 1, "H", 2]), False)
verify(possible_path([3, "H", 2, 1]), False)
verify(possible_path(["H", 2, 3, "H"]), False)
verify(possible_path([1, 3, 4]), False)

或使用 zip(或者您可以使用 itertools.pairwise,因为 python 3.10)和 all:

def possible_path(lst):
    d = {1: [2], 2: [1,"H"], "H": [2,4], 4: ["H",3], 3: [4]}
    return all(y in d[x] for x, y in zip(lst, lst[1:]))