[How To] find longest strings in array
|Problem: Given an array of strings, return another array containing all of its longest strings. For Example, given [“ccd”, “bb”, “hg”, “aaa”, “kbj”, “f”] array, should be returned [“ccd”, “aaa”, “kbj”].
Solution 1
def longestStrings(array): longestLength = 0 result = [] for word in array: if len(word) == longestLength: result.append(word) if len(word) > longestLength: longestLength = len(word) result = [word] return result
Solution 2
def longestStrings(array): longestLength = max(len(word) for word in array) result = [word for word in array if len(word) == longestLength] return result