python - 高阶函数。以前未引用的本地变量
问题描述
我正在研究社交网络图问题。目标是找到距离目标人N度的人列表。目标人员 ID 为 47
数据看起来像{(47,28):12,(47,15):13,(15,15):19,(15,47):6,(15,28):31,(28,16):67,(16,16):74 }
。密钥对意味着两个人彼此认识。价值观在这里并不重要。
例如,当 n = 1 时,预期结果为 [28,15]
在下面运行代码时,出现错误“以前未引用本地变量“对手””
# Helper.
# Input: [] of source people.
# Output: [] of all who are friends with source people.
# ! Contains duplicates and but not self.
def opponent(data, source):
opponent = []
for s in source:
for key in data:
if s in key:
opponent.append(key ^ set([s]))
return [next(iter(i)) for i in opponent if i]
def people_with_separation_number(data, n):
if n == 0:
return [47]
else:
source = people_with_separation_number(data,n-1)
opponent = opponent(data,source)
accum = [47]
for i in range(1,n+1):
seen = accum.extend(people_with_separation_number(data,i))
result = set(opponent) - (set(opponent)&set(seen))
return result
print(people_with_separation_number(data,0)) # expected answer [47]
print(people_with_separation_number(data,1)) # expected answer [28,15]
print(people_with_separation_number(data,2)) # expected answer [16]
解决方案
推荐阅读
- spring-boot - flyway 从 4.X 升级到 5.x 再次运行已经运行的迁移脚本
- reactjs - 在不刷新页面的情况下反应路由
- c# - 在 RH 上角使用“X”时,应用程序未在调试模式下关闭
- php - 如何将一篇文章发布到多种文章类型?
- python - 在python中查找某些时间范围内的时间重叠
- puppeteer - 使用 xvfb 可以达到的最大分辨率是多少?
- windows - Gammu - gammu - 在windows下检测?
- python - 我使用 Colab 和 Plotly,我想保存一个 Plotly 图 - 如何在 Colab 中安装 plotly-orca?
- python - Python 3 项目没有给我我正在寻找的结果
- ruby-on-rails - 猴子修补 ActiveStorage::Attachment 丢失