[本文出自天外归云的博客园]

今天一个朋友去面试,下面是一道测试工程师面试题(来自搜狗):

自己写了解法:

# -*- coding: utf-8 -*-
import re def filter_log(target,the_log):
r = '['+target+']'
target_dic = {}
for one in target:
target_dic[one] = 0
for one in re.findall(r, the_log):
target_dic[one] += 1
return min(target_dic.items(), key=lambda x: x[1])[1] if __name__ == '__main__':
the_log = "CRIUCEXPLORESGOUIUSCRIUdSCdRIdUdddS"
target = "CRIUS"
print filter_log(target,the_log)

写了解法以后感觉到没有显现出python的优势,找大师兄学了一些pythonic的写法,比如将一个列表创建成字典有以下两种写法可以一行搞定(初始化每个key的value为0):

#target_dic = {one:0 for one in list}
#target_dic = dict.fromkeys(list, 0)

例如min()可以根据key也可以不用,不用key的话语句就会更短一些:

import re,collections

the_log = "CRIUCEXPLORESGOUIUSCRIUdSCdRIdUdddS"
target = "CRIUS"
print min(collections.Counter(re.findall('['+target+']', the_log)).items(), key=lambda x: x[1])[1]
#print min(collections.Counter(re.findall('['+target+']', the_log)).values())

如果测试字符串“CRIUCEXPLORESGOUIUSCRIUdSCdRIdUdddS”自备的话,两行搞定:

import re,collections
print min(collections.Counter(re.findall('[CRIUS]', raw_input("Input:"))).values())

原来还有import内置函数!现在就一行了:

print min(__import__('collections').Counter(__import__('re').findall('[CRIUS]', raw_input("Input:"))).values())

是不是特别好玩!O(∩_∩)O哈哈哈~

最新文章

  1. JavaScript slice() 方法
  2. UIWebView的使用
  3. setTimeout和setInterval
  4. objective-c数组笔记
  5. NCPC 2013: Dance Reconstruction
  6. Unity-WIKI 之 AllocationStats(内存分配)
  7. js功能汇总
  8. Oracle学习网址
  9. UIScrollView解决touchesBegan等方法不能触发的解方案
  10. C# Windows Phone 8 WP8 开发,将WebClient的DownloadStringCompleted事件改成非同步的awiat方法。
  11. memcached and redis
  12. Linux设置静态IP【转】
  13. Python解决 从1到n整数中1出现的次数
  14. SpringBoot+Mybatis+Freemark 最简单的例子
  15. 【cocos 2d-x】VS2012+win7+cocos2d-x3.0beta2开发环境配置
  16. defer、return、返回值,这三者的执行逻辑
  17. C# 中将月份格式化为英语缩写格式
  18. 批量获取oracle的表和表字段注释【原】
  19. sql存储过程进行条件筛选
  20. Javascript执行流总结

热门文章

  1. PHP中目录解析函数
  2. 游戏开发之UE4添加角色到场景中
  3. ORACLE的Dead Connection Detection浅析
  4. HTML5中将video设置为背景的方法
  5. 使用Grafana 展示Docker容器的监控图表并设置邮件报警规则
  6. KB奇遇记(1):开篇
  7. POJ1221(整数划分)
  8. 笑谈ArcToolbox (3) ArcToolbox的一亩三分地
  9. 众人拾柴火焰高之Tomcat集群
  10. Ninject之旅之十三:Ninject在ASP.NET MVC程序上的应用(附程序下载)