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.
8 ответов
+ 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!
+ 5
print(max(input().split(), key=len))
+ 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
+ 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
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.
0
《 Nicko12 》 Buddy, but we have to find the longest Word not the common word. The question just asks to find the longest word
0
Oh ok, sorry, my bad I misread. I'll try again.
0
《 Nicko12 》 thanks Buddy it worked