发现一个学Python的好网站 https://py.checkio.org
第一题大概意思就是找出一个字符串中出现频率最高字母
我的思路也是直接,弄个字典,遍历字符串,将键值对填进字典里,健就是字母,值就是出现了几次,再查下字典里最大的值即可。
上我的代码
import re, string
def checkio(text):
#先变小写再排序
text ="".join((lambda x:(x.sort(),x)[1])(list(text.lower())))
dicts = {}
#遍历字符串
for i in text[0:]:
#筛选只有字母的
if i.isalpha():
#有则加一,无则为一
if i in dicts:
dicts[i] = dicts[i] + 1
else:
dicts[i] = 1
test = 0
a = ''
#遍历所有key值
for j in dicts.keys():
#大的留下,小的直接过
if dicts[j] > test:
test = dicts[j]
a = j
#返回值
return a
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert checkio("Hello World!") == "l", "Hello test"
assert checkio("How do you do?") == "o", "O is most wanted"
assert checkio("One") == "e", "All letter only once."
assert checkio("Oops!") == "o", "Don't forget about lower case."
assert checkio("AAaooo!!!!") == "a", "Only letters."
assert checkio("abe") == "a", "The First."
print("Start the long test")
assert checkio("a" * 9000 + "b" * 1000) == "a", "Long."
print("The local tests are done.")
外国的大神是这样写的 两句话
def checkio(text):
#我懂第一步是变小写
text = text.lower()
#what? max不就是个比大小的?咋这么牛逼呢?
return max(string.ascii_lowercase, key=text.count)
其中 string.ascii_lowercase这个打印结果是abcdefghijklmnopqrstuvwxyz,
这个就是字母表小写字母排序输出,key=text.count 先要理解count这个方法 ,count() 方法用于统计字符串里某个字符出现的次数。可选参数为在字符串搜索的开始与结束位置,那就是我挨个在count里传入字母,它也挨个返回这个字母返回的次数。max里就是比大小咯,输出第一个。神奇!!!