Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Checking the contents of the tuple in Python

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading