itertools combinations函数

https://www.hackerrank.com/challenges/iterables-and-iterators/problem
problem
The itertools module standardizes a core set of fast, memory efficient tools that are useful by themselves or in combination. Together, they form an iterator algebra making it possible to construct specialized tools succinctly and efficiently in pure Python.

To read more about the functions in this module, check out their documentation here.

You are given a list of lowercase English letters. For a given integer , you can select any indices (assume -based indexing) with a uniform probability from the list.

Find the probability that at least one of the indices selected will contain the letter: ‘’.

Input Format

The input consists of three lines. The first line contains the integer , denoting the length of the list. The next line consists of space-separated lowercase English letters, denoting the elements of the list.

The third and the last line of input contains the integer , denoting the number of indices to be selected.

Output Format

Output a single line consisting of the probability that at least one of the indices selected contains the letter:’’.

Note: The answer must be correct up to 3 decimal places.

Constraints

All the letters in the list are lowercase English letters.

Sample Input

4
a a c d
2
Sample Output

0.8333

solution:

from itertools import combinations
n = int(input())
l =input().split()
k = int(input())
c = list(combinations(l, k))
# d = [i for i in c if 'a' in i]
d = list(filter(lambda x:'a' in x, c))
print ('{0:.4f}'.format(   len(d)/len(c)   ))

combinations随机组合列表里的元素
print (list(combinations([1,2,3], 2)))
result: [(1, 2), (1, 3), (2, 3)]

filter 将函数应用于后面的列表
print (list(filter(lambda a:a>2, [1,2,5,6,0])))
result [5, 6]

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值