首页 > 解决方案 > 高阶函数。以前未引用的本地变量

问题描述

我正在研究社交网络图问题。目标是找到距离目标人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]

标签: pythonpython-3.x

解决方案


推荐阅读