简体   繁体   中英

Finding the longest length of word in the list Python

Can you help me understand how this code works?

words = ["dan","kar","dream","adsadsadad","AHAHAHAHAHAHHHAAHAHA","aaa"]
best = 0
for index in range(len(words)):
    if len(words[index]) > len(words[best]):
        best = index
print(words[best])

For every word in the list, check that, if the length of the current word is more than the longest word we have seen so far then it is the new longest word.

Basically, instead of storing the lengths of the words in a list, we are checking it every time & then determining the word, with the longest length.

Above code works like this

  1. first Initialising best = 0
  2. Now iterating the for loop based on length of the list from 0 to 5 index ,
  3. if length of word for [0 ]index greater than Length of word index [best] means best will replace as current index,like that
  4. process will goes on till the for loop end
  5. At end print current best index value word

We have this code:

words = ["dan","kar","dream","adsadsadad","AHAHAHAHAHAHHHAAHAHA","aaa"]
best = 0
for index in range(len(words)):
    if len(words[index]) > len(words[best]):
        best = index
print(words[best])

Let's break this down a bit:

words = ["dan","kar","dream","adsadsadad","AHAHAHAHAHAHHHAAHAHA","aaa"]

This creates a list of words of various lengths.

best = 0

This variable holds the index to the word with the longest length we have encountered so far.

for index in range(len(words)):

The for statement will iterate through the list of words.

    if len(words[index]) > len(words[best]):

This if statement checks if the word at the current index is longer than the word at the index to which best points to.

        best = index

If the new word is longer than our best word so far, we set the best word to the new index.

print(words[best])

We print the word by utilizing the saved best word index.

best = 0 :

This means that, so far, the longest length in the list is 0. This value will be updated in the loop.

for index in range(len(words)) :

In your example, len(words) is 6, that is the number of words in your list 'words'. So the loop will go from index 0 ("dan") to 5 ("aaa").

Then the program checks if the length of the current word is greater than the length of the longest word so far. If it is longer, then you save the current index in the variable 'best'.

Finally, it prints the word corresponding to that index.

The for loop there iterates through the dynamically created list of indices from 0 to the length of words , which is 6. (range does not include the 6th index.)

Then if the length of the word that is in the index of value of the index is greater than the previously selected longest word, the new index of the longest word will be the current index.

Trace: best = 0 index = 0

Is the length of the words[index] (dan) greater than the length of words[best] (dan)? No. Proceed to next iteration.

best = 0 index = 1

Is the length of the words[index] (kar) greater than the length of words[best] (dan)? No. Proceed to next iteration.

best = 0 index = 2

Is the length of the words[index] (dream) greater than the length of words[best] (dan)? Yes. The new value of best is 2.

Then repeat the process until you finished executing the process

Your code is iterating over indices 0, 1, 2, ..., length-1 of list named words .

First time it is considering the max length string as the one which is at index 0 ie by setting best = 0 .

In each iteration it is comparing the lengths of current string present at index best with string present at index index and resetting the value of rest with new index if condition len(words[index]) > len(words[best]) gets evaluated to True .

In this way, after completion of for loop, you are getting an exact index of max length string.

So if your intension is to get max length, you can also calculate max length string and its length.

Below is the single line of code using reduce() and lambda that you can use to get length of max length string available in list.

>>> words = ["dan","kar","dream","adsadsadad","AHAHAHAHAHAHHHAAHAHA","aaa"]
>>> 
>>> reduce(lambda a, b: a if len(a) > len(b) else b, words)
'AHAHAHAHAHAHHHAAHAHA'
>>> 
>>> len(reduce(lambda a, b: a if len(a) > len(b) else b, words))
20
>>> 

There's already a number of good responses, but here's another using the lesser known key argument to max :

>>> words = ["dan","kar","dream","adsadsadad","AHAHAHAHAHAHHHAAHAHA","aaa"]
>>> max(words, key=len)
'AHAHAHAHAHAHHHAAHAHA'

Edit : I missed the comment from @Indominus in my initial response, so he should get all the credit :P

It's nothing but 'Linear Search' algorithm.

let's take the same example with not words but numbers.

nums = [ 9,5,8,6,3,4 ]

#assuming the first element as our biggest number
biggest_number = nums[0]

for i in range(0, len(nums)):
  if nums[i] > biggest_number:  #comparing each number with the biggest number we assumed
    biggest_number = nums[i]   #if our current number bigger than biggest_number then replace the value

print(biggest_number)

In the code, you're just comparing elements one by one with all other elements and checking if the current element satisfies the condition, which in this case is whether it is bigger than others or not, and replacing the values where it does not; and finally returning the last value which satisfied the condition.

In your code, it's about length of the string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM