Given a list of lists, write a Python program to count the number of sublists containing the given element x.
Input : lst = [1, 3, 5], [1, 3, 5, 7], [1, 3, 5, 7, 9]] x = 1 Output : 3 Input : lst = (['a'], ['a', 'c', 'b'], ['d']) x = 'a' Output : 2
Approach #1 : Naive Approach
Count the number of lists containing x. Initialize count to 0, then start a for loop and check if x exists in each list or not. If yes, increment count.
Approach #2 : List comprehension (Alternative for naive)
A simple one-liner list comprehension can also do the job by simply converting the above mentioned Naive approach into one-liner for loop.
Approach #3 : Using
We can use Counter to count how many lists ‘x’ occurs in. Since we don’t want to count ‘x’ for more than once for each inner list, we’ll convert each inner list to sets. After this, join those sets of elements into one sequence using
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.