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

Find the length of the longest list that a contains a certain character in another list

I have a list [[1],[2,3],[a, b, c], [1, a, b, 3]]
I need to find the longest list that contains the char a.
I have the code to find the lenght of the longest list, but can’t implement the search for the a char:

def find_max_list(list):
    list_len = [len(i) for i in list]
    print(max(list_len))

find_max_list(your_list)

>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

Try this:

def find_max_list(lst):
    lst_len = max(('a' in x, len(x)) for x in lst)
    print(lst_len)

This piece of code creates a list of tuples where the first element is True or False (depending on ‘a’ being present or not in the list) and the second element is just the length of a list. Then you calculate the max, keeping in mind that False < True, and that first elements are evaluated first.

An alternative approach is to filter out those lists not containing ‘a’:

def find_max_list(lst):
    lst_len = max(len(x) for x in lst if 'a' in x)
    print(lst_len)
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