How to find friends
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行的语法特性
随机推荐
- MySQL的SQL_CALC_FOUND_ROWS真的很慢么?
分页程序一般由两条SQL组成: SELECT COUNT(*) FROM ... WHERE .... SELECT ... FROM ... WHERE LIMIT ... 如果使用SQL_CALC ...
- QT类的继承结构
QT类的继承结构 QT的类 core 数据集合 QString 几何类 QPoint QSize QRectangle 系统类 QColor QFont QImage QIcon QCursor QB ...
- WustOJ 1575 Gingers and Mints(快速幂 + dfs )
1575: Gingers and Mints Time Limit: 1 Sec Memory Limit: 128 MB 64bit IO Format: %lldSubmitted: 24 ...
- 潘石屹的SOHO小报猝死
东莞时报多媒体数字报刊平台 潘石屹的SOHO小报猝死
- JavaScript Function 函数深入总结
整理了JavaScript中函数Function的各种,感觉函数就是一大对象啊,各种知识点都能牵扯进来,不单单是 Function 这个本身原生的引用类型的各种用法,还包含执行环境,作用域,闭包,上下 ...
- [置顶] IOS7状态栏StatusBar官方标准适配方法
IOS7状态栏StatusBar官方标准适配方法 hello,大家好,ios7正式版已经发布,相信大家都在以各种方式来适配ios7. 如果你已经下载了xcode5,正准备使用,你会发现各种布局的改变. ...
- [Redux] Extracting Presentational Components -- TodoApp
Finally, I just noticed that the to-do app component doesn't actually have to be a class. I can turn ...
- 细说php(六) 数组
一.数组概述 1.1 数组是复合类型 1.2 数组中能够存储随意长度的数据, 也能够存储随意类型的数据 二.数组的类型 2.1 索引数组: 下标是顺序整数作为索引 <?php $user[0] ...
- 使用Qt Style Sheets制作UI特效
引言 作为一套GUI框架,Qt是非常强大的.(注:Qt 不仅是一套优秀的GUI框架,同时也是一套出色的应用程序框架).在UI的制作方面Qt为广大开发者提供了一套强大而易用的工具,她就是——Qt Sty ...
- oracle to_char()及to_date()函数使用
to_char(x[,format]) :将x转换成字符串,可以使用format参数来格式化字符串输出. to_date(x[,format]) :将字符串x转换成日期,可以使用format匹配要转换 ...