Iterables and Iterators

Sort by

recency

|

887 Discussions

|

  • + 0 comments

    Enter your code here. Read input from STDIN. Print output to STDOUT

    import itertools N = int(input()) letters = input().split() k = int(input()) listed_combinations = list(itertools.combinations(letters,k))

    count = 0

    for i in listed_combinations: if "a" in i: count +=1

    print(count/len(listed_combinations))

  • + 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}")

  • + 0 comments

    import itertools

    n = int(input())

    letters = input().split()

    k = int(input())

    count = letters.count('a')

    total_combinations = len(list(itertools.combinations(range(n),k)))

    favorable_combinations = 0

    for comb in itertools.combinations(range(n), k):

    if any(letters[i] == 'a' for i in comb):
        favorable_combinations += 1
    

    probability = favorable_combinations/total_combinations print(f"{probability:.4f}")

  • + 1 comment

    Please, can anybody answer me, why itertools.combinations() is fine, but interpreter cannot recognize itertools.ifilter()? I see that using sum with a list comprihension is easier, I used built in filter() with success, though.

  • + 0 comments
    from itertools import combinations
    N = int(input())
    A = list(input().split())
    K = int(input())
    B = list(combinations(A, K))
    count = sum(1 for x in B if 'a' in x)
    print(count/len(B))