我如何在图中添加边(初学者)

我想在当前图形中添加边这是我的图形代码


def mGraph():

    graph = {'A': {'B': 1, 'C': 2},

             'B': {'C': 2, 'D': 1},

             'C': {'D': 1},

             'D': {'C': 2},

             'E': {'F': 1},

             'F': {'C': 2}}

    return graph

这是添加边功能


def add_edge(graph, aa1, aa2):

         graph[aa1].update()[aa2]

         graph[aa2].update()[aa1]

         return graph

我要求用户输入第一个节点和第二个节点


def main():

    graph = mGraph()

    option = ''

    while option != 'terminate':

        print(" a. Display")

        print(" c. Add Edges")

        option = input("Enter your option:")


        if option == "a":

            print(graph)


        if option == "c":

            a1 = input("First Edge")

            a2 = input("Second Edge")

            print(add_edge(graph, a1, a2))



main()

我想将两条边链接到当前图形并想修改它们。如果用户在“First Edge”中输入 A,在“Second Edge”中输入 D。我想看到图表中的变化。用户输入应该反映在图表上。


我有这样的错误


Traceback (most recent call last):

  File "C:......", line 52, in <module>

    main()

  File "C:......", line 49, in main

    print(add_edge(graph, a1, a2))

  File "C:......", line 25, in add_edge

    graph[aa1].update()[aa2]

TypeError: 'NoneType' object is not subscriptable


缥缈止盈
浏览 101回答 1
1回答

杨魅力

试试这个 :def add_edge(graph, aa1, aa2):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;first_value = graph[aa1].copy()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;for k,v in first_value.items():&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if aa2 in k:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; graph[aa1].update({aa2:v+1})&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; graph[aa1].update({aa2:1})&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;second_value = graph[aa2].copy()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;for k,v in second_value.items():&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if aa1 in k:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; graph[aa2].update({aa1:v+1})&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; graph[aa2].update({aa1:1})&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return graph
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go