在python中创建知道其他朋友的朋友的字典 [英] Creating dictionaries of Friends that know other Friends in python

查看:161
本文介绍了在python中创建知道其他朋友的朋友的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



编写一个功能网络()参数。第一个参数是组中的人数,第二个参数是定义朋友的元组对象列表。假设人数由0到n-1。例如,元组(0,2)表示人0是与人2的朋友。该功能应该将人的分区打印成友谊圈。以下显示了函数的几个示例运行:

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

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



社交网络1是{3,4}



我真的很失落关于如何启动这个程序,任何提示将不胜感激。

解决方案

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

这是我正在寻找的,如果有人关心。


In any group of people there are many pairs of friends. Assume that two people who share a friend are friends themselves. (Yes, this is an unrealistic assumption in real life, but let's make it nevertheless). In other words, if people A and B are friends and B is friends with C, then A and C must also be friends. Using this rule we can partition any group of people into friendship circles as long as we know something about the friendships in the group.

Write a function networks() that takes two parameters. The first parameter is the number of people in the group and the second parameter is a list of tuple objects that define friends. Assume that people are identified by numbers 0 through n-1. For example, tuple (0, 2) says that person 0 is friends with person 2. The function should print the partition of people into friendship circles. The following shows several sample runs of the function:

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

Social network 0 is {0,1,2}

Social Network 1 is {3,4}

I am honestly pretty lost on how to start this program, any tips would be greatly appreciated.

解决方案

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.

这篇关于在python中创建知道其他朋友的朋友的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆