一道面试题引发的pythonic
2024-10-10 06:14:12
[本文出自天外归云的博客园]
今天一个朋友去面试,下面是一道测试工程师面试题(来自搜狗):
自己写了解法:
# -*- 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哈哈哈~
最新文章
- JavaScript slice() 方法
- UIWebView的使用
- setTimeout和setInterval
- objective-c数组笔记
- NCPC 2013: Dance Reconstruction
- Unity-WIKI 之 AllocationStats(内存分配)
- js功能汇总
- Oracle学习网址
- UIScrollView解决touchesBegan等方法不能触发的解方案
- C# Windows Phone 8 WP8 开发,将WebClient的DownloadStringCompleted事件改成非同步的awiat方法。
- memcached and redis
- Linux设置静态IP【转】
- Python解决 从1到n整数中1出现的次数
- SpringBoot+Mybatis+Freemark 最简单的例子
- 【cocos 2d-x】VS2012+win7+cocos2d-x3.0beta2开发环境配置
- defer、return、返回值,这三者的执行逻辑
- C# 中将月份格式化为英语缩写格式
- 批量获取oracle的表和表字段注释【原】
- sql存储过程进行条件筛选
- Javascript执行流总结