Checking the contents of the tuple in Python

Question:

How would I be able to write a function that checks a tuple if it contains at least 2 H elements in the list. So for the example below there are 2 tuples in A that contain 2 H elements {('H', 'H', 'H', 'T') and ('T', 'H', 'H', 'T')}?

A = [('H', 'H', 'H', 'T'), ('T', 'T', 'T', 'T'), ('T', 'H', 'H', 'T'), ('T', 'T', 'T', 'H'),]
Asked By: Teoman Selcuk

||

Answers:

One simple option would be this:

len([item for item in A if item.count('H') >= 2])

We use list comprehension to get a list of all the items with at least two instances of ‘H’ in them, and then check the length of that list.

Another option would be this:

sum(1 for item in A if item.count('H') >= 2)

Which follows a similar idea but without going through the pointless "list->len" step: we just use the generator directly instead.

Showing both because Python is cool! 🙂

Answered By: Shay

Use the tuple.count() method to count the number of H elements. Then you can use sum() to total the number of times this is at least 2.

A = [('H', 'H', 'H', 'T'), ('T', 'T', 'T', 'T'), ('T', 'H', 'H', 'T'), ('T', 'T', 'T', 'H'),]
num_2H = sum(item.count('H') >= 2 for item in A)
print(num_2H) # prints 2
Answered By: Barmar