HackerRank - Python部分

来源:互联网 发布:淘宝追加评价怎么看 编辑:程序博客网 时间:2024/06/06 02:04

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

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

from collections import Counterfrom functools import reduceimport operatordef 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 heapqfrom collections import Countercount = [(-v,k)for k,v in Counter(input()).items()]count.sort()for i in count[:3]:    print(i[1],-i[0])
0 0
原创粉丝点击