+ 1

Returning the longest word in Python

Dear all! My code should return the longest word in a sentence provided by the user and i should not use "max" or "split" in this exercise. Where's the mistake in my code? txt = input() count1 = 0 count2 = 0 for word in list(txt): for char in word: count1 =+1 if count2 <= count1: count2 = count1 longest_word = word print(longest_word) EDIT: SOLUTION WITHOUT MAX AND SPLIT: txt = input()+' ' count = 0 max_length = 0 word = '' for char in txt: if char != ' ': count += 1 word += char else: if max_length <= count: max_length = count longest_word = word word = '' count = 0 print(longest_word) SOLUTION WITH MAX AND SPLIT: txt = input() longest_word = max(txt.split(), key=len) print(longest_word)

26th Jun 2021, 5:36 PM
Stefano Morelli
Stefano Morelli - avatar
4 ответов
+ 2
here is a code with 3 variations and 4 outputs: https://code.sololearn.com/cDUQNNYilTPW/?ref=app 1) print 1st longest 'word' (any not space consecutive char) 2) print 1st longest 'word' (any consecutive letters) 3) print all longest 'words' (any consecutive letter) 4) print same 'words' list, but without repetition and sorted finally, there is hint to check other chars than letters as well... example input to provide and see differences of each output: "there are 'words' without letters and spaces only and with somes letters suit wich occurs twice"
26th Jun 2021, 9:58 PM
visph
visph - avatar
+ 2
Using for loops on this question can be really tricky, I tried for almost 4hours. but I found a good way. try splitting your input and then use key=len method as shown below: txt = input()# enter a string # Finding longest word longest_word = max(txt.split(), key=len) print("The longest word is ", longest_word, " ==> ", len(longest_word), "characters")
26th Jun 2021, 6:14 PM
Allan 🔥STORMER🔥🔥🔥🔥
Allan 🔥STORMER🔥🔥🔥🔥 - avatar
+ 1
for w in list(txt): will extract individual charecters from txt to w. But Not words as you expecting... So you get only 1 charecter all time.
26th Jun 2021, 6:12 PM
Jayakrishna 🇮🇳