这两题都是用了字符串和Couter计数,写一块了。
1042 题意:
输入一串字符串,有任意字符。统计字符串中出现次数最多的字母,统计时不用区分大小写,但是输出要小写字母。
思路:
- 直接用 Counter 计数
- 主要问题是排序,按次数从大到小排序,如果有并列,就输出字母序小的,也就是说一个关键词从大到小,一个关键词从小到大,可以把先数字取负,然后按升序排列,后得到的结果正是所需的数字从大到小,字母从小到大。
输入:
This is a simple TEST. There ARE numbers and other symbols 1&2&3…
输出:
e 7
import string
from collections import Counter
pat = string.ascii_uppercase + string.ascii_lowercase
mystr = input()
mystr = [ch.lower() for ch in mystr if ch in pat] # 把所有字母提取出来
counts = Counter(mystr)
ans = sorted(counts.items(), key=lambda x:(-x[1], x[0])) # 主要体现在这
print(ans[0][0], ans[0][1])
1057 题意:
给定一串字符串,规定英文字母 a-z (不分大小写)对应1-26,问字符串中所有字母对应数的和,转为二进制后有多少个 0 和 1 。
思路:
- 打表得到字典。
- 得到
sum
之后通过 bin()函数直接转化。 - 最后用 Counter 计数
import string
from collections import Counter
lower = string.ascii_lowercase
mystr = input().lower()
mystr = [ch for ch in mystr if ch in lower] # 把字母提取出来
dic = dict()
for i in range(1, 27): # 得到字典 a-1
dic[chr(i+96)] = i
sum = 0
for ch in mystr:
sum += dic[ch]
if sum == 0: # 值得注意的是,如果sum=0,Counter计数时,0的个数会为1,不符合实际情况,所以要特判
print(0, 0)
else:
ans = bin(sum)[2:] #转化为二进制时开头是 0b
counts = Counter(ans)
print(counts['0'], counts['1'])