Iterables and Iterators

  • + 0 comments

    from itertools import combinations

    Reading input

    n = int(input())

    letters = input().split()

    k = int(input())

    Finding the indices where the letter 'a' occurs

    a_indices = [i for i, letter in enumerate(letters) if letter == 'a']

    Generating all combinations of k indices from the list

    total_combinations = list(combinations(range(n), k))

    Counting the combinations that contain at least one 'a' index

    favorable_combinations = [ combo for combo in total_combinations if any(i in a_indices for i in combo) ]

    Calculating the probability

    probability = len(favorable_combinations) / len(total_combinations)

    Printing the result with 4 decimal places print(f"{probability:.4f}")