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. SPOJ375.QTREE树链剖分

    题意:一个树,a b c 代表a--b边的权值为c.CHANGE x y  把输入的第x条边的权值改为y,QUERY x y 查询x--y路径上边的权值的最大值. 第一次写树链剖分,其实树链剖分只能说 ...

  2. 股票市场问题(The Stock Market Problem)

    Question: Let us suppose we have an array whose ith element gives the price of a share on the day i. ...

  3. WPF与输入法冲突研究之一:百度输入法会导致WPF程序的崩溃!

    在学习和使用了WPF一段时间之后,有点感觉WPF是个不太成熟的框架,不知道是我学的太肤浅,还是WPF得BUG太多! >>>>>>>模拟场景<<&l ...

  4. python学习Processing

    # -*- coding: utf-8 -*-__author__ = 'Administrator'import bisect#排序说明:http://en.wikipedia.org/wiki/i ...

  5. wcf简单的创建和运用

    创建一个控制台应用程序,命名为wcftest,并在同一解决方案中添加一个wcf服务应用程序 在wcf项目中会自动生成Service1.svc服务程序文件和IService1.cs契约接口 IServi ...

  6. mysql下用户和密码生成管理

    应用上线,涉及到用户名和密码管理,随着上线应用的增加,用户名和密码的管理设置成为一个问题.还要对用户赋权,于是想着写一个脚本来管理,看到同事写的一个脚本,满足需求.思路大致是字母替换为数字,账号根据库 ...

  7. [Regex Expression] Find Sets of Characters

    Regular Expression Character Classes define a group of characters we can use in conjunction with qua ...

  8. NVL函数(NVL,NVL2,NULLIF,COALESCE)

    NVL 语法:NVL( expr1, expr2) 功能:如果expr1为NULL,则NVL函数返回expr2的值,否则返回expr1的值,如果两个参数的都为NULL ,则返回NULL. 注意事项:e ...

  9. UIView的setNeedsLayout, layoutIfNeeded 和 layoutSubviews 方法之间的关系解释

    转自:http://blog.csdn.net/meegomeego/article/details/39890385 layoutSubviews总结 ios layout机制相关方法 - (CGS ...

  10. 如何制作windows服务安装包

    以下转自:http://blog.csdn.net/chainan1988/article/details/7087006 Window服务的安装有两个方式: 一.命令安装          通过命令 ...