python count(), lower(), ord(), chr(), isalpha()

Question:

You are given a text, which containsdifferent english letters and punctuation symbols. You should find the mostfrequent letter in the text. The letter returned must be in lower case.
While checking for the most wanted letter, casing does not matter, so for thepurpose of your search, "A" == "a". Make sure youdo not count punctuation symbols, digits and whitespaces, only letters.

If you have two or more letters withthe same frequency, then return the letter which comes first in the latinalphabet. For example -- "one" contains "o", "n","e" only once for each, thus we choose "e".

Input: A text for analysis as a string(unicode for py2.7).

Output: The most frequent letter inlower case as a string.

Precondition:
A text contains only ASCII symbols.
0 < len(text) ≤ 105



Code:

方法一:

def checkio(text):
   tmp = 0
   tmpch = None
   text = text.lower()
   for char in text:
       if ord(char) < 97 or ord(char) > 122:
           continue
       if text.count(char) > tmp:
            tmp = text.count(char)
           tmpch = char
       if text.count(char) == tmp and ord(char) < ord(tmpch):
           tmpch = char
return tmpch

 

方法二:

def checkio(text):
   str = text.lower()
   letters = {i:str.count(i) for i in str if i.isalpha()}
   frequency = [letters[i] for i in letters]
   most_frequent = [i for i in letters if letters[i] == max(frequency)]
   return min(most_frequent)

 

检验:

if __name__ == '__main__':
   #These "asserts" using only for self-checking and notnecessary for auto-testing
   assert checkio("Hello World!") == "l", "Hellotest"
   assert checkio("How do you do?") == "o", "O ismost wanted"
   assert checkio("One") == "e", "All letter onlyonce."
   assert checkio("Oops!") == "o", "Don't forgetabout lower case."
   assert checkio("AAaooo!!!!") == "a", "Onlyletters."
    assertcheckio("abe") == "a", "The First."
   print("Start the long test")
   assert checkio("a" * 9000 + "b" * 1000) =="a", "Long."
   print("The local tests are done.")



扩展:

str.count(sub, start, end)   用于统计字符串里某个字符出现的次数,可选参数为在字符串搜索的开始与结束位置。

参数:

sub -- 搜索的子字符串

start -- 字符串开始搜索的位置。默认为第一个字符,第一个字符索引值为0。

end -- 字符串中结束搜索的位置。字符中第一个字符的索引为 0。默认为字符串的最后一个位置。

返回值:子字符串出现次数

 

 

str.lower( )   转换字符串中所有大写字符为小写。

参数:无

返回值:返回将字符串中所有大写字符转换为小写后生成的字符串。

 

ord( )  字符与asscii转换

参数:asscii字符(65~90为26个大写英文字母,97~122号为26个小写英文字母)

返回值:对应的十进制整数

 

chr()  字符与asscii转换

参数: 0 - 256 的一个整数,可以是10进制也可以是16进制的形式

返回值:当前整数对应的asscii字符

 

str.isalpha()  检测字符串是否只由字母组成。

参数:无

返回值:如果字符串至少有一个字符并且所有字符都是字母则返回 True,否则返回



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值