一道面试题引发的pythonic

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

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

自己写了解法:

# -*- 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哈哈哈~

posted @ 2017-03-14 18:16  天外归云  阅读(407)  评论(0编辑  收藏  举报