Longest word problem. What is the error of this code? I can't find it. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Longest word problem. What is the error of this code? I can't find it.

txt = input() a=txt.split(' ') for i in range(0,len(a)): if i==len(a)-2 : if len(a[i])>len(a[i+1]): m=a[i] else: m=a[i+1] else: if len(a[i-2])>len(a[i]): m=a[i-2] else: m=a[i] print (m) #your code goes here

26th Aug 2021, 4:48 AM
Hirushi Premarathna
3 Answers
+ 2
You are making it too complicated! simple logic is, create a varibale which will keep the track of longest word. and create another varibale which will keep track of count of each word..ex. count =text[0] iterate over input by splitting it and then check count for each word if count is greater than previous count then replace count with current count.. and also replace the longest word variable with current iteration word if count > count.. Hope u got the logic!
26th Aug 2021, 4:56 AM
Ratnapal Shende
Ratnapal Shende - avatar
+ 1
Hirushi Umm, you're over-complicating it. Here are two ways to do it: # With Python's features print(max(input().split(), key = len)) # Bare-coding inp = input() + " " max = "" present = "" for x in inp: if x == " ": if len(present) > len(max): max = present present = "" else: present += x print(max) # I hope that this answer helps you with your query. I'm open to any corrections. Happy coding !
26th Aug 2021, 5:47 AM
Calvin Thomas
Calvin Thomas - avatar
+ 1
txt = input() a= txt.split(" ") i=1 if len(a[0])>= len(a[1]): var1= a[0] else: var1 = a[1] while i < (len(a)-1): if len(var1) >= len(a[i]): pass else: var1 = a[i] i+=1 print(var1) Thank you very much. i have done it with ur help.
2nd Sep 2021, 3:40 AM
Hirushi Premarathna