Python函数式编程解决单词中字符频统计问题

就是输入一个单词比如“science”,最后返还的结果是[ 'c','e'], 2/7。大意就是在这个单词中一共有两个字母重复的频率最高,分别是c和e,这个highest relative frequency是2/7


其实达到基本要求只要一行就可以实现:

>>> func=lambda w: '{0},{1[0]}/{2}'.format(*zip(*filter(lambda x:x[1]>1, __import__('collections').Counter(word).most_common())),len(w))
>>> func('science')
"('c', 'e'),2/7"
>>> func('protocol')
"('o',),3/8"
>>> 

更为完善一些的写法是下面这样的:


#coding=utf-8

from collections import Counter

def freq(word):
    counter = Counter(word).most_common()
    freq_chars = counter[0:1] + list(filter(lambda x: x[1]>1, counter[1:]))   
    return '{0} => {1},{2[0]}/{3}'.format(word,*zip(*freq_chars),len(word))

test_cases = 'science protocol word c collections 0 '.split()
print('\n'.join(map(freq, test_cases)))


结果:

Python 3.6.2 (v3.6.2:5fd33b5, Jul  8 2017, 04:57:36) [MSC v.1900 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> 
science => ('c', 'e'),2/7
protocol => ('o',),3/8
word => ('w',),1/4
c => ('c',),1/1
collections => ('c', 'o', 'l'),2/11
0 => ('0',),1/1
>>> 



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值