Python基础100题打卡24天

题目一百

当有些语言输出时,可能会有重复的部分。对于每个单词,输出其出现的次数。输出顺序应与单词外观的输入顺序相对应。
请参阅示例输入/输出以获得澄清。
如果给出以下字符串作为程序的输入:
4 bcdef abcdefg bcde bcdef
输出:
3 2 1 1

代码实现

n = int(input("请输入字符串长度:"))
word_lst = []
word_dict = {}
for i in range(n):
    word = input("请输入字符串:")
    if word not in word_lst:
        word_lst.append(word)
    word_dict[word] = word_dict.get(word,0) + 1

print(len(word_lst))
for word in word_lst:
    print(word_dict[word],end=" ")

运行结果

请输入字符串长度:4
请输入字符串:bcdef
请输入字符串:abcdefg
请输入字符串:bcdebcdef
请输入字符串:bcdef
3
2 1 1 

题目一百零一

你将得到一个字符串,你的任务是计算字符串中字母的频率,并按频率的降序打印这些字母。
如果给出以下字符串作为程序的输入:
aabbbccde
输出:
b 3 a 2 c 2 d 1 e 1

代码实现

方法一:

word = input("请输入需要统计的字符:")
word_set = set(word)
word_lst = []
for i in word_set:
    word_lst.append([i,word.count(i)])

arr_word = sorted(word_lst,key=lambda x: (-x[1],x[0]))
print(arr_word)

方法二:

word = input("请输入需要统计的字符:")
dct = {}
for i in word:
    dct[i] = dct.get(i, 0) + 1

dct = sorted(dct.items(), key=lambda x: (-x[1], x[0]))
for i in dct:
    print(i[0], i[1])

方法三:

s = list(input("请输入需要统计的字符:"))

dict_count_ = {k: s.count(k) for k in s}
list_of_tuples = [(k, v) for k, v in dict_count_.items()]
list_of_tuples.sort(key=lambda x: x[1], reverse=True)

for item in list_of_tuples:
    print(item[0], item[1])

运行结果

请输入需要统计的字符:aabbbccde
b 3
a 2
c 2
d 1
e 1
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值