首页 > 解决方案 > Python如何找到第二个连接?

问题描述

A 的人脉是 B、C、D 和 E。A 的第二个人脉(与 A 的人脉有联系但不直接与 A 联系的人)是 F 和 G。H 是 A 的第三个人脉,不应返回。A 的 get_second_connections(self) 方法应该返回一个包含 F 和 G 的集合。你能给我一些关于这个问题的提示吗?我有一个集合中的所有连接,init 方法获取名称和连接。集合中的添加连接方法存储名称。如何找到 get_second_connection?

connections = sets
def add_connection(self, other):

    self.connections.add(other)

标签: pythonclassmethods

解决方案


我会将其保持在较低的技术水平;如果你愿意,你可以把它塞进一个理解中。

遍历一阶连接列表。对于每个连接,获取它们的一阶连接并将它们添加到当前的二阶集合中——我称之为friend_of_friend.

def second_connections(self):
    for other in self.connections:
        self.friend_of_friend.union(other.connections)

推荐阅读