大菠萝

大菠萝-ama+sor

统计字符串中元音的个数-Python

统计一段字符串中元音出现的次数,元音指['a','e','i','o','u']。使用两种方法,正则表达式和遍历字符串。

正则表达式函数为:

def byre(str):
    'by re'
    p=re.compile(r'[aeiou]')
    print len(p.findall(str))

遍历函数为:

def bypass(str):
    'by traversing'
    list=['a','e','i','o','u']
    print sum(1 for x in str if x in list)

写完后,想测试下二者运行时间上有没有区别,写个计算运行时间的函数time()。

def runtime(fun):
    start=clock()
    fun
    end=clock()
    print 'Run %s Time:%s' %(fun,end-start)

随机,大量字符串,统计两个函数运行时间。二者运行时间相似,正则表达式稍微占点优势。

完整的代码下载:lenstringcount.py (592 bytes)


相关阅读

tags: ,

Posted by benben on November 17,2008 7:41 PM in 程序设计 ||Comment(3)
3个脚印
第1脚: guotie November 18,2008 1:54 PM

原来是你啊,呵呵

第2脚: qutotjasid March 25,2009 8:47 PM

Hello! You are good!

第3脚: 啊啊 March 25,2009 8:47 PM

杀杀傻逼!

留言




早起的鸟儿有虫子吃


e.g. "大菠萝"