首页 > 编程语言 > 详细

一道面试题引发的pythonic

时间:2017-03-14 19:40:23      阅读:215      评论:0      收藏:0      [点我收藏+]

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

技术分享

自己写了解法:

# -*- coding: utf-8 -*-
import re

#从整体log中过滤出有用的部分,缩小搜索范围
def filter_log(the_log):
    r = r[CRIUS]
    return re.findall(r, the_log)

#统计每个目标字符出现过的最少次数,即最少出现过几次完整log
def 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,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哈哈哈~

一道面试题引发的pythonic

原文:http://www.cnblogs.com/LanTianYou/p/6549932.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!