HackerRank - Python部分

这篇博客探讨了如何在HackerRank的Python部分解决关于计算字符串中特定字符概率、游戏规则分析及统计最多出现字符的题目。通过公式计算随机选取k个元素包含'a'的概率,并解析游戏得分策略,以及处理字符串统计问题的注意事项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

给定一个字符序列,计算出随机选取k个元素中包含’a’的概率。

本题属于简单题,主要思路就是利用公式1C(Nm,k)/C(N,k)来得到概率。

from collections import Counter
from functools import reduce
import operator
def C(n,k):
    return reduce(operator.mul, range(n - k + 1, n + 1)) /reduce(operator.mul, range(1, k +1))
N = int(input())
seq = input().split(' ')
k = int(input())
m = Counter(seq)['a']
prob = 1 - C(N-m,k)/C(N,k)
print('{0:.4f}'.format(prob))

===========================================

Game Rules

Both players are given the same string, .
Both players have to make substrings using the letters of the string .
Stuart has to make words starting with consonants.
Kevin has to make words starting with vowels.
The game ends when both players have made all possible substrings.

Scoring
A player gets +1 point for each occurrence of the substring in the string .

思路很简单,就是计算有多少个字串是以元音或者非元音开头的。那么每发现一个符合条件的字母,就求出以它为首的字串的数量:它到最后一个字母的距离+1。最后求和即可。

vow = ['A','E','I','O','U']
s = input()
n = len(s)
a = sum((n-i)for i,ch in enumerate(s) if ch in vow)
b = sum((n-i)for i,ch in enumerate(s)if ch not in vow)
if a==b:print('Draw')
else:
    print( 'Kevin {0}'.format(a) if a > b else 'Stuart {0}'.format(b) )

统计一个字符串里有出现次数最多的3个字符,如果相同次数的字符超过3个,则要按照字母顺序选。

这道题不能简单的使用most_common(3),因为有可能前3的值超过3个,必须取得所有值之后再排序。
import heapq
from collections import Counter
count = [(-v,k)for k,v in Counter(input()).items()]
count.sort()
for i in count[:3]:
    print(i[1],-i[0])

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值