0
hey guys my project longest word in python tutorial is working but solo learn don't accept it, why
txt = input() li='' r=0 for i in range (len(txt)): if txt[i]==' ': li=txt[i+1:r] r=r+i print(str(li))
8 Respostas
+ 1
Khorchani Yassine , as I said you don't check the length of each word with loop and store for example the current longest word in variable. Or split the sentence by whitespace and sort it by length of each word. Then you need to print the last word.
+ 1
I think a solution using split and max would be the preferred way, but i tried to go with your idea (as i understood it).
There were some issues with the indices, it didn't consider the last word and didn't check for the length
def fun(txt):
li=''
r=0
for i in range(len(txt)):
if i==len(txt)-1 or txt[i+1]==' ':
if i-r+1 > len(li):
li=txt[r:i+1]
r=i+1
return li
print(fun(input()))
0
Khorchani Yassine , in fact it doesn't work. You output the last word of the sentence, which is not guaranteed to be the longest. Where in your code do you check for the current word length?
0
yes i test it many times and it works
0
if you want try it
0
Khorchani Yassine , I tried it before my post and it obviously doesn't work as it should.
0
u don't know why ?
0
You just dont remember that after " must be print "