Creating dictionaries of Friends that know other Friends in python

醉酒当歌 提交于 2019-12-06 04:27:52
Blckknght

One efficient data structure you can use to solve this is a disjoint set, also known as a union-find structure. A while back I wrote one for another answer.

Here's the structure:

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

Here's how you can use it to solve your problem:

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))
jfs

Here's a solution based on connected components in a graph (suggested by @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))))

Example:

networks(5, [(0,1),(1,2),(3,4)])
# -> Social network 0 is {0,1,2}
# -> Social network 1 is {3,4}
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

This is what I was looking for if anybody cares.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!