How to find friends

思路简单,编码不易

 1 def check_connection(network, first, second):
2 link_dictionary = dict()
3
4 for link in network:
5 drones = link.split('-')
6
7 link_dictionary.setdefault(drones[0], []).append(drones[1])
8 link_dictionary.setdefault(drones[1], []).append(drones[0])
9
10 future = []
11 visited = []
12 future.append(first)
13
14 while future:
15 current = future.pop()
16 visited.append(current)
17
18 extend = link_dictionary[current]
19
20 if second in extend:
21 return True
22
23 for each in extend:
24 if each not in visited:
25 future.append(each)
26
27 return False

使用dict存储每个人的直接关系, 如{lyly : [lala, gege]}; 使用两个list, 其中一个表示已遍历过的人, 另一个表示即将遍历的人;

另外python中的二维数组可以这么定义: connection = [[False for col in range(5)] for row in range(5)], 即一个5*5的数组, 原先尝试过这么定义error = [[False] * 5] * 5, 发现只要修改了

error[0][0], 那么error[1][0], error[2][0] ...都修改了, 因为[False] * 5产生了一个一维数组, 而外面的*5只是产生了5个引用因此, 无论修改哪一个其余的均会改变.

观摩下大神的代码

 1 def check_connection(network, first, second):
2 setlist = []
3 for connection in network:
4 s = ab = set(connection.split('-'))
5 # unify all set related to a, b
6 for t in setlist[:]: # we need to use copy
7 if t & ab: # check t include a, b
8 s |= t
9 setlist.remove(t)
10 setlist.append(s) # only s include a, b
11
12 return any(set([first, second]) <= s for s in setlist)

将每条关系作为set, 若关系间交集不为空, 则求关系间的并集, 即关系圈;

最后查看first与second是否在某个关系圈中;

充分利用了set的操作, &交, |并, <=子集;

还有第12行的语法特性

随机推荐

  1. http://wiki.apache.org/tomcat/HowTo

    http://wiki.apache.org/tomcat/HowTo Contents Meta How do I add a question to this page? How do I con ...

  2. SQL之用户自定义函数

    关于SQL Server用户自定义的函数,有标量函数.表值函数(内联表值函数.多语句表值函数)两种. 题外话,可能有部分朋友不知道SQL Serve用户自定义的函数应该是写在哪里,这里简单提示一下,在 ...

  3. 再看ADO对象模型

    在敲学生管理系统之前,我们就学习过ADO的有关知识.但是昨天被问到ADO的几个对象,顿时无言!为什么会出现这样的结果呢,明明是学习过了,而且也实践过(红皮书的五个例子).这充分说明了,在以往的学习过程 ...

  4. [Redux] Extracting Container Components -- Complete

    Clean TodoApp Component, it doesn't need to receive any props from the top level component: const To ...

  5. install samba on crux without net.

    1. 解压文件 tar -xvfz samba-.tar.gz 2. 进入目录 cd samba- 3. 配置 ./configure 4. 编译 make 5. 安装 make install

  6. My way to Python - Day012 - 消息中间件

    消息中间件介绍 消息中间件的概念 消息中间件是在消息传输过程中保存消息的容器.消息中间件在将消息从它的源中继到它的目标时充当中间人的作用.队列的主要作用是提供路由并保证消息的传递:如果发生消息接收者不 ...

  7. js Date扩展Format()函数

    Date.prototype.Format = function (formatStr) { var str = formatStr; var Week = ['日', '一', '二', '三', ...

  8. vs2015体验

    项目结构 bower.json Bower依据此文件安装需要的前端的包 package.json NPM依据此文件获取对应的包 project.json 包含用于NPM的"poststore ...

  9. Windows命令行(DOS命令)教程-4(转载)http://arch.pconline.com.cn//pcedu/rookie/basic/10111/15325_3.html

    2. md md是英文make directory(创建目录)的缩写 [功能] 创建一个子目录 [格式] md [C:]path [举例] 用md 建立一个叫做purple的目录 3. cd cd是英 ...

  10. No1_8.类和对象2_Java学习笔记_对象

    对象 /**** * *一.对象 *1.概念:对象是由类抽象出来的,对象可以操作类的属性和方法解决问题,了解对象的创建.操作和消亡很必要: *2.对象的创建: * a. new操作符创建:每实例化一个 ...