1

I have a list of sublists of anagrams such as

L = [['terrible', 'elbirret'],
     ['supermonster', 'retsnomrepus'],
     ['you', 'uoy', 'oyu'],
     ['pears', 'reaps', 'spear', 'spera']]

How do I write a function that will give me the sublist or anagram group that has the longest anagrams.

i.e. if the list were

L = [['spear', 'pears', 'reaps'], ['monster', 'sternom']]

it would give me

['monster', 'sternom']
3
  • 2
    By longest anagrams you mean the string length of anagrams? Commented Dec 11, 2014 at 3:52
  • So by "longest anagram" do you mean the anagram with the most letters or the anagram with the most possible combinations? Commented Dec 11, 2014 at 3:53
  • Yes I meant string length. Most letters. Thanks!! Commented Dec 11, 2014 at 4:03

1 Answer 1

4

Using max with a key function to get the list with longest strings:

>>> L = [['spear', 'pears', 'reaps'], ['monster', 'sternom']]
>>> max(L, key=lambda xs: len(xs[0]))
['monster', 'sternom']

UPDATE

What if there were multiple sublists with longest of the same length?

Find the maximum length. Filter sublist based on the length:

>>> L = [['largest', 'artlegs'], ['spear', 'pears', 'reaps'], ['monster', 'sternom']]
>>> M = max(len(xs[0]) for xs in L)
>>> [xs for xs in L if len(xs[0]) == M]
[['largest', 'artlegs'], ['monster', 'sternom']]
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much! I had one more question. What if there were multiple sublists with longest of the same length? How would I get it to print the multiple sublists out?
You can alwyas flatten your list before processing its values.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.