0

Python Longest Word Problem Solution check

Question: in given string, find the longest Word and output the same Sample Input: Coding is awesome. Sample Output: awesome ##MYCODE txt = input() txt.strip() a=txt.replace(',','') a=a.split(' ') for i in a: i.strip() max=len(a[0]) for i in range(1,len(a)): if len(a[i])>max: max=len(a[i]) pos=i print(a[pos]) MY code passes 3 out of 4 test. But failed one. Can anyone find the error.

25th Dec 2020, 7:14 AM
Prashant Kumar
Prashant Kumar - avatar
8 Answers
+ 2
txt = input() a = txt.split() max=len(a[0]) pos = 0 for i in range(1,len(a)): if len(a[i])>max: max=len(a[i]) pos=i print(a[pos]) - - - - - - - - - - - - - - - - - The problem is when the first element is the longest, it will cause an error, so to solve this, you must set "pos" to 0 as default. Because For Example: INPUT: learning is fun - - - - - - - - - - - - - The max variable has the length of the first element but in the for loop, the "pos" will only have a value if other element is longer than it, otherwise "pos" will not have a value because the condition never came True. And by the way, that can be implemented as this. print(max(input().split(), key=len)) Just additional info for useful functions. I hope helped you. Happy Coding!
25th Dec 2020, 7:38 AM
noteve
noteve - avatar
+ 5
print(max(input().split(), key=len))
25th Dec 2020, 10:12 AM
David Ashton
David Ashton - avatar
+ 2
i think i gpt it right here txt = input() a = txt.split() max=len(a[0]) pos = 0 for i in range(1,len(a)): if len(a[i])>max: max=len(a[i]) pos=i print(a[pos]) happy coding
7th Sep 2021, 7:58 AM
mthabisi
mthabisi - avatar
+ 1
It would be better if you please give the description of that project.Sorry for asking because I am using sololearn web. A possible problem may be there might be '.' in the sentence which your code is not removing
25th Dec 2020, 7:22 AM
Adnan Chowdhury
Adnan Chowdhury - avatar
0
Adnan Chowdhury I have written the whole question here. It's a python course project on sololearn, project no 5. May be it is not able to remove other special characters as you mentioned.
25th Dec 2020, 7:26 AM
Prashant Kumar
Prashant Kumar - avatar
0
《 Nicko12 》 Buddy, but we have to find the longest Word not the common word. The question just asks to find the longest word
25th Dec 2020, 7:30 AM
Prashant Kumar
Prashant Kumar - avatar
0
Oh ok, sorry, my bad I misread. I'll try again.
25th Dec 2020, 7:36 AM
noteve
noteve - avatar
0
《 Nicko12 》 thanks Buddy it worked
25th Dec 2020, 7:40 AM
Prashant Kumar
Prashant Kumar - avatar