0

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)
martineau
  • 119,623
  • 25
  • 170
  • 301
Matei Piele
  • 572
  • 2
  • 15
  • 1
    Does this answer your question? [List comprehension with if statement](https://stackoverflow.com/questions/15474933/list-comprehension-with-if-statement) – mkrieger1 Feb 11 '22 at 20:15
  • 1
    do you want to find the longest list that contains "a" or do you want to find the length of the longest list that contains "a". The title and content seem to be saying different things. –  Feb 11 '22 at 20:16
  • Do `max(len(i) for i in your_list if "a" in i)`. The `if "a" in i` part makes it so we only include lists that contain `"a"`. – Samwise Feb 11 '22 at 20:17
  • If I find the longest list I can also fins the lenght of it. – Matei Piele Feb 11 '22 at 20:18
  • Having a variable called `list` is not a great idea, because it hides the `class list` which brings us list support. Better rename it. – Thomas Weller Feb 11 '22 at 20:18
  • Also, please provide a [mre], an example that is complete and can actually run. The list definition you gave us does not contain characters. Please include `your_list = [[1],[2,3],['a', 'b', 'c'], [1, 'a', 'b', 3]]` in the code example – Thomas Weller Feb 11 '22 at 20:19
  • I just want to find the longest list that contains the char "a" – Matei Piele Feb 11 '22 at 20:23
  • if you want to find the longest list containing "a", then you can use a generator expression which filters lists with "a" in `max` and `key=len` (this means `max` function compares lengths): `max((i for i in lst if 'a' in i), key=len)` –  Feb 11 '22 at 20:29

2 Answers2

0

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)
Riccardo Bucco
  • 13,980
  • 4
  • 22
  • 50
-1

Try this:

import collections

def find_max_list(a_list):
    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
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61