python - 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)
解决方案
我会将其保持在较低的技术水平;如果你愿意,你可以把它塞进一个理解中。
遍历一阶连接列表。对于每个连接,获取它们的一阶连接并将它们添加到当前的二阶集合中——我称之为friend_of_friend
.
def second_connections(self):
for other in self.connections:
self.friend_of_friend.union(other.connections)
推荐阅读
- python - 为什么 sqlalchemy 不创建我的其他表
- sql-server - 查询以获取所有未全额支付的发票
- puppeteer - Puppeteer 屏幕截图未在网页上呈现正确的字体?
- docker - clickhouse:在启动时创建物化视图(docker)
- python - 有没有更快的方法将 SQL 查询的结果从 Teradata 放入 pandas 数据框中?
- folium - FeatureGroup'对象没有属性'iterrows
- javascript - 无论如何,是否可以在不托管的情况下呈现网站并共享它?
- bash - Bash - 如何替换文件中第 m 行的第 n 个字符串?
- python - 如何解决 Checkmarx 针对 python 代码“args=parser.parse_args()”的“命令注入”问题?
- sql - 我想用 rdbms 函数的表中的字符串更新