Python递归实现

2024-06-11 21:02:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试在Python中使用更多的递归,因为我在这门语言中越来越有经验。我正在使用networkx并尝试从传递到函数中的节点获取所有网络连接(以及关系数据)。我能够使用集合和3 for循环(凌乱)让它工作,并且正在尝试找出如何使用递归来更有效地解决它。你知道吗

如果有人能告诉我哪里出了问题,或者如何确定基本情况等等。。。我们将不胜感激。你知道吗

常规方法:

import networkx as nx
G = nx.Graph()
nodes = ["Gur","Qing","Samantha","Jorge","Lakshmi","Jack","John","Jill"]
edges = [("Gur","Qing",{"source":"work"}),
         ("Gur","Jorge", {"source":"family"}),
        ("Samantha","Qing", {"source":"family"}),
        ("Jack","Qing", {"source":"work"}),
        ("Jorge","Lakshmi", {"source":"work"}),
        ("Jorge","Samantha",{"source":"family"}),
        ("Samantha","John", {"source":"family"}),
        ("Lakshmi","Jack", {"source":"family"}),
        ("Jack","Jill", {"source":"charity"}),
        ("Jill","John",{"source":"family"})]
G.add_nodes_from(nodes)
G.add_edges_from(edges)

def get_connections(graph,node,relationship):
    connections_bunches = graph.edges(nbunch=nodes, data=True)
    print("Conn Bunches", connections_bunches, len(connections_bunches))   # a list of edges that are tuples
    ##GET A LIST OF NODES\EDGES BASED ON RELATIONSHIP
    RelConnections = [i for i in connections_bunches if i[2]['source'] == relationship]  #creates list of edges that match relationship para
    ##USE SETS TO MAINTAIN UNIQUE NODES
    ConnectionSet = set()    # Should be: [John, Jill, Samantha, Qing, Jorge, Gur].
    FinalConnectionSet = ConnectionSet
    ReturnConnectionSet = FinalConnectionSet
    ##LOOP THROUGH THE RELATIONSHIP LIST ADDING TO SETs
    for i in RelConnections:
        node1 = i[0]
        node2 = i[1]
        if node1 == node or node2== node:
            ConnectionSet.add(node1)
            ConnectionSet.add(node2)
    for i in RelConnections:
        node1 = i[0]
        node2 = i[1]
        if node1 in ConnectionSet:
            FinalConnectionSet.add(node2)
        elif node2 in ConnectionSet:
            FinalConnectionSet.add(node1)
    for i in RelConnections:
        node1 = i[0]
        node2 = i[1]
        if node1 in FinalConnectionSet:
            ReturnConnectionSet.add(node2)
        elif node2 in FinalConnectionSet:
            ReturnConnectionSet.add(node1)
    return list(FinalConnectionSet)#ConnectionSet#size()

[“约翰”、“古尔”、“萨曼莎”、“吉尔”、“清”、“豪尔赫”]

递归尝试:

def get_connectionsRecursive(graph, node, relationship):
    #print(node+"\n"+relationship+'\n', graph.edges())
    edges = graph.edges(nbunch=nodes, data=True)
    print("EDGES\n", edges, "LEN\n", len(edges))

    node_connections_set = set()

    if len(edges) == 0: #base case, all edges have been processed

         return list(node_connections_set)

    else:
        for tup in edges:
            #print(tup[-1]['source'])
            if tup[-1]['source'] != relationship:
                #continue
                #print("SOURCE NOT FAMILY", tup)
                graph.remove_edge(tup[0],tup[1])
            elif node in tup:
                print("NODE FOUND!", tup)
                node_connections_set.add(tup[0])
                node_connections_set.add(tup[1])

                graph.remove_edge(tup[0], tup[1])

        get_connectionsRecursive(graph, node, relationship)

    print("NEW LEN", len(edges))
    return graph.edges(), node_connections_set
    #print(get_connections(G,'John','family'))

print(get_connectionsRecursive(G,'John','family'))

似乎我做了很多额外的处理,我的递归调用一直出错,因为list len(edges)停留在4(所有非关系数据)。任何见解都是值得赞赏的。你知道吗

[('Gur','Jorge',{'source':'family'}),('Qing','Samantha',{'source':'family'}),('Samantha','Jorge',{'source':'family'}),('Lakshmi','Jack',{'source':'family'})]

短暂性脑缺血发作


Tags: inaddnodesourceconnectionsfamilygraphprint