Home > Blockchain >  Code for creating an array of longest words not working [Python]
Code for creating an array of longest words not working [Python]

Time:12-03

I am trying to write python code that takes words from an array and makes a new array that includes all of the longest words of the previous array. I can't find where the problem is, but whenever I run this, it just eats a ton of RAM but doesn't work (it should print the words Good and Cool). Does anyone see the problem?

words = ["Good", "Bad", "Cool"]
def longest_word():
    longest = [""]
    for word in words:
        for word2 in longest:
            if len(word) > len(word2):
                longest.clear()
                longest.append(word)
            elif len(word) == len(word2):
                longest.append(word)
    print(str(longest_word))
longest_word()

CodePudding user response:

You could do this in a list comprehension using the max function like this:

words = ["Good", "Bad", "Cool"]
max_length = len(max(words,key=len))
longest = [word for word in words if len(word) == max_length]

The max function will return the string with the most characters because of the key=len argument, and then you compare the length of each word in your list to the length of the returned string from max. If the lengths match then it adds the word to the longest list.

Edit: Changed my answer to reflect @NathanielFord's suggestion

CodePudding user response:

You could just loop through once getting the length of each word and saving it to a longestWord variable if it's greater. Then loop through a second time to add it to the array if it's the same length as the longestWord variable.

CodePudding user response:

While I wouldn't go about it this way, you're pretty close with a few simplifications:

words = ["Good", "Bad", "Cool"]
def longest_word():
    longest = []  # Don't add an empty word here
    l = len(words[0])  # Remember the length of the first word
    for word in words:
        if len(word) > l:  # If the next word is longer than the longest length found so far...
            longest = []  # Reset your list
            longest.append(word)  # Add the word
            l = len(word)  # Remember the new longest length
        elif len(word) == l:
            longest.append(word)
    
    print(longest)
longest_word()

There are two reasons not to iterate over the longest list. The first is that you're actively modifying that list - if you clear it in the middle of doing so it will lead to strange results. Secondly, it's much more computationally expensive - you might get O(n^2) time in the worst case. The only info you need is the length so far of the longest word, so remember that and update it instead of trying to recheck each element of your longest list. (After all, you know all those elements have to equal each other!)

  • Related