在python中创建了解其他朋友的朋友词典

时间:2013-03-11 05:39:11

标签: python python-3.x social-networking dictionary

在任何一群人中都有很多朋友。假设两个分享朋友的人自己就是朋友。 (是的,这在现实生活中是一个不切实际的假设,但让我们做到这一点)。换句话说,如果人A和B是朋友而B是C的朋友,那么A和C也必须是朋友。使用此规则,只要我们了解群组中的友谊,我们就可以将任何一群人划分为友谊圈。

编写一个带有两个参数的函数networks()。第一个参数是组中的人数,第二个参数是定义朋友的元组对象列表。假设人们通过数字0到n-1来识别。例如,元组(0,2)表示人0是人2的朋友。该函数应该将人的分区打印到友谊圈中。以下显示了该函数的几个示例运行:

>>>networks(5,[(0,1),(1,2),(3,4)])#execute

社交网络0是{0,1,2}

社交网络1是{3,4}

老实说,我很遗憾如何启动这个程序,任何提示都会非常感激。

3 个答案:

答案 0 :(得分:1)

可用于解决此问题的一种有效数据结构是disjoint set,也称为union-find结构。不久前我为another answer写了一个。

这是结构:

class UnionFind:
    def __init__(self):
        self.rank = {}
        self.parent = {}

    def find(self, element):
        if element not in self.parent: # leader elements are not in `parent` dict
            return element
        leader = self.find(self.parent[element]) # search recursively
        self.parent[element] = leader # compress path by saving leader as parent
        return leader

    def union(self, leader1, leader2):
        rank1 = self.rank.get(leader1,1)
        rank2 = self.rank.get(leader2,1)

        if rank1 > rank2: # union by rank
            self.parent[leader2] = leader1
        elif rank2 > rank1:
            self.parent[leader1] = leader2
        else: # ranks are equal
            self.parent[leader2] = leader1 # favor leader1 arbitrarily
            self.rank[leader1] = rank1+1 # increment rank

以下是如何使用它来解决您的问题:

def networks(num_people, friends):
    # first process the "friends" list to build disjoint sets
    network = UnionFind()
    for a, b in friends:
        network.union(network.find(a), network.find(b))

    # now assemble the groups (indexed by an arbitrarily chosen leader)
    groups = defaultdict(list)
    for person in range(num_people):
        groups[network.find(person)].append(person)

    # now print out the groups (you can call `set` on `g` if you want brackets)
    for i, g in enumerate(groups.values()):
        print("Social network {} is {}".format(i, g))

答案 1 :(得分:0)

以下是基于connected components in a graph的解决方案(由@Blckknght建议):

def make_friends_graph(people, friends):
    # graph of friends (adjacency lists representation)
    G = {person: [] for person in people} # person -> direct friends list
    for a, b in friends:
        G[a].append(b) # a is friends with b
        G[b].append(a) # b is friends with a
    return G

def networks(num_people, friends):
    direct_friends = make_friends_graph(range(num_people), friends)
    seen = set() # already seen people

    # person's friendship circle is a person themselves 
    # plus friendship circles of all their direct friends
    # minus already seen people
    def friendship_circle(person): # connected component
        seen.add(person)
        yield person

        for friend in direct_friends[person]:
            if friend not in seen:
                yield from friendship_circle(friend)
                # on Python <3.3
                # for indirect_friend in friendship_circle(friend):
                #     yield indirect_friend

    # group people into friendship circles
    circles = (friendship_circle(person) for person in range(num_people)
               if person not in seen)

    # print friendship circles
    for i, circle in enumerate(circles):
        print("Social network %d is {%s}" % (i, ",".join(map(str, circle))))

示例:

networks(5, [(0,1),(1,2),(3,4)])
# -> Social network 0 is {0,1,2}
# -> Social network 1 is {3,4}

答案 2 :(得分:0)

def networks(n,lst):
groups= []
for i in range(n)
    groups.append({i})
for pair in lst:
    union = groups[pair[0]]|groups[pair[1]]
    for p in union:
        groups[p]=union
sets= set()
for g in groups:
    sets.add(tuple(g))
i=0
for s in sets:
    print("network",i,"is",set(s))
    i+=1

如果有人关心,这就是我所寻找的。