Advertisements
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'),]
>Solution :
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