Python:简单的图形表示。测试失败

问题描述 投票:0回答:1

我的字典图形表示有问题。这是我的代码:

from typing import List

class GraphAdjacencyDictionary:

    def __init__(self, number_of_vertices: int):
        self.dic = {}
        for i in range(number_of_vertices):
            self.dic[i] = []

    def add_new_edge(self, vertex1: int, vertex2: int):
        self.dic[vertex1].append(vertex2)
        self.dic[vertex2].append(vertex1)
        print(self.dic)

    def get_list_of_adjacent_vertices(self, vertex: int) -> List[int]:
        res = []
        for i in self.dic:
            res.append(1) if i in self.dic[vertex] else res.append(0)
        return res

    def get_number_of_adjacent_vertices(self, vertex: int) -> int:
        return len(self.dic[vertex])

    def is_edge(self, vertex1: int, vertex2: int) -> bool:
        return vertex2 in self.dic[vertex1]

因此,其中一项测试在 get_number_of_adjacent_vertices 上失败 - 断言错误:5 == 4

我认为我的任务是正确的,并且有一个假设,测试中存在错误,请您确认或反驳我的理论

python testing graph
1个回答
0
投票

问题的根源可能在于您的

add_new_edge()
函数,其中测试用例可能包含重复的条目。

def add_new_edge(self, vertex1: int, vertex2: int):
    if vertex2 not in self.dic[vertex1]:
        self.dic[vertex1].append(vertex2)
        self.dic[vertex2].append(vertex1)
    print(self.dic)

尽管在字典中使用

set
而不是
list
更好。因为它不存储重复的值。

© www.soinside.com 2019 - 2024. All rights reserved.