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

Time:02-12

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)

CodePudding user response:

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)

CodePudding user response:

Try this:

def find_max_list(a_list):
import collections
most_common=[]
for i in a_list:
    a_counter = collections.Counter(i)
    most_common.append(a_counter.most_common()) 
maxfinal=[a[:1] for a in most_common]
    
return maxfinal
  • Related