2

在任何一群人中,都有很多对朋友。假设分享朋友的两个人本身就是朋友。(是的,这在现实生活中是一个不切实际的假设,但让我们仍然这样做)。换句话说,如果 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}

老实说,我对如何启动这个程序非常迷茫,任何提示将不胜感激。

4

3 回答 3

1

可以用来解决此问题的一种有效数据结构是 a disjoint set,也称为union-find结构。不久前,我写了一个作为另一个答案

这是结构:

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))
于 2013-03-11T06:44:30.910 回答
1
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

如果有人在乎,这就是我一直在寻找的东西。

于 2013-03-21T15:53:05.723 回答
0

这是一个基于图中连接组件的解决方案(由@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}
于 2013-03-12T04:36:48.247 回答