+ 3

Longest word in python

txt = input() list = txt.split() a=len(list) b = 0 while b < a : if len(list[b])>len(list[b-1]): word = str(list[b]) b=b+1 print(word) This code works in python app, but doesnt work in this Solo learn app, why? Please help me.

23rd Jan 2021, 9:11 PM
Sardor
Sardor - avatar
4 Réponses
+ 3
This is what I did... txt = input() #this attaches the user input to the variable txt longest = txt.split() #.split() takes one large string and separates it into a sortable list longest_word = max(longest, key=len) '''This is the tricky part. max() takes the largest values. longest is the split variable of the input. key=len will organize them from smallest to largest. example = [1,22,0000] max(example, key=len) = 0000 as the largest. Alternatively could key=len and take longest[-1] since it was organized from smallest to largest, is largest is at the end of the list. simple doing longest_word = max(longest) from what I can tell takes in longest[0], so doing key=len forces it to actually go through the list fir the largest word''' print(longest_word) #prints the longest word found there, now you did it with just 4 lines of code.
25th Jan 2021, 2:39 AM
Catalyst
+ 8
Because b=b+1 should be inside while loop not outside of it.
23rd Jan 2021, 9:28 PM
Abhay
Abhay - avatar
+ 5
Thank you
23rd Jan 2021, 10:03 PM
Sardor
Sardor - avatar
+ 2
Thank you Catalyst, for very good explanation
25th Jan 2021, 3:14 AM
Sardor
Sardor - avatar