首页 > 代码库 > 一道面试题引发的pythonic

一道面试题引发的pythonic

一道测试工程师面试题(来自搜狗):

技术分享

自己写了解法:

# -*- coding: utf-8 -*-import re#从整体log中过滤出有用的部分,缩小搜索范围def filter_log(the_log):    r = r[CRIUS]    return re.findall(r, the_log)#统计每个目标字符出现过的最少次数,即最少出现过几次完整logdef check_count(target,target_log):    target_dic = {}    for one in target:        target_dic[one] = 0    for one in target_log:        target_dic[one]+=1    return min(target_dic.items(), key=lambda x: x[1])[1]if __name__ == __main__:    the_log = "CRIUCEXPLORESGOUIUSCRIUdSCdRIdUdddS"    target_log = filter_log(the_log)    target = "CRIUS"    count = check_count(target,target_log)    print count

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

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

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

import re,collectionsthe_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,collectionsprint 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哈哈哈~

一道面试题引发的pythonic