Find out the longest word | SoloLearn: Learn to code for FREE!

+1

Find out the longest word

I want to find out the longest word of a string. However it turnout a TypeError: 'int' object is not iterable. How can I correct the coding? Thanks https://code.sololearn.com/cbKwR5MGZsX5/?ref=app

10/24/2020 3:35:21 PM

Joe Ma

15 Answers

New Answer

+7

https://code.sololearn.com/cJSlK0D24SPT/?ref=app You can get everything you need to know from here.

+5

text = input().split() length = [len(x) for x in text] maximum = max(length) text_index = length.index(maximum) print(text[text_index])

+4

txt = "this is an awesome text example" d = {i:len(i) for i in txt.split()} ml = max([d[i] for i in d]) print(d, end=2*'\n') print(f'max. number of characters: {ml}', end=2*'\n') for i in d: if d[i] == ml: print(i)

+4

The suggestion of Bahha🐧 prints only the first word with the max. length. This I demonstrate in the following example where the max number is 7 and this applies to the words "awesome" and "example": txt = "this is an awesome text example" k = txt.split() maxWordLength = max(len(word) for word in k) print(max(k, key=len))

+4

Maxwell Anderson Yes, "fails" was not the correct word. I wanted to say that it does not give a complete answer. The answer is correct in parts. It prints only the first word which have the max. number of characters. But the later words of the same character count will be neglected.

+3

print(max(k, key=len)) no need for a loop

+3

txt = input() #your code goes here txt_list = txt.split(" ") #print(txt_list) dictman= {i:len(i) for i in txt_list} maxman = max(dictman[i] for i in txt_list) for i in dictman: if dictman[i] == maxman: print(i)

+1

I don't see how Bahha🐧 solution fails, it prints out the longest word with or without multiple words of the same max length. Their answer is also the most concise.

0

Joe Ma , you can do it this way 🐱 https://code.sololearn.com/c7yXFPkjY4of/?ref=app

0

Hi, You used a split method that returns a list of word in your initial string, if you want to use a for loop you will need to compare the length of each list item with the other and keep storing the longest you have seen so far. At end of the loop you can print the answer. https://code.sololearn.com/cpW3GfK1hihk/?ref=app

0

Davide logos382 it only output the result of last loop which is True, not really meet the goal, but thanks for your help :)

0

txt = "this is an awesome text" #your code goes here k = txt.split() j='' for i in k: if len(i) > len(j): j=i print(j)

0

txt = input() #your code goes here def l(f): k=max(f,key=len) return k f=txt.split() print(l(f))

-3

I can help you by c++

-4

ممم