HackerRank Python: Iterables and Iterators

Iterables and Iterators

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.

You are given a list of N lowercase English letters. For a given integer K, you can select any K indices (assume 1-based indexing)

with a uniform probability from the list.

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

3개의 input을 입력 받습니다.

첫번째는 integer이며 리스트의 길이를 의미합니다. 1 <X<= 10의 범위를 갖습니다.

두번째는 공백으로 구분된 소문자 알파벳입니다.

세번째는 조합을 구성하는 수를 의미합니다. 1<=Y<=X의 범위를 갖습니다.

이 세가지를 통해 a 알파벳의 속한 조합의 확률을 구합니다.

Sample Input

4

a a c d

2

조합을 구성하는 수는 2개임며 a a c d를 활용하여 조합을 만든 후 a가 포함된 조합의 확률을 구합니다.

from itertools import combinations

#itertools의 combinations는 조합을 생성해줍니다.

A = int(input())
B = input().split() #공백으로 구분되어 있기 때문에 공백을 제외한 알파벳을 split()을 통해 입력받습니다.
C = int(input())

D = list(combinataions(B,C)) #알파벳으로 길이 2를 갖는 조합을 생성합니다.
E = filter(lambda c: 'a' in c, D) # lambda를 이용해서 D리스트 안의 tuple 원소 중 a가 포함된 tuple만 filter합니다.

print("{0:.3}".format(len(list(E))/len(D))) # E리스트 길이를 D리스트로 나눠 확률을 구합니다.