longest Word | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

longest Word

can anybody tell me why this is printing error. function longestWord(str) { var one = str.split(" "); var two = ""; for (var three of one) { if (three.length > two.length) two = three; } return two; } longestWord("the boy who could be king"); console.log(two);

11th Jul 2020, 10:06 PM
Ibrahim Yusuf
Ibrahim Yusuf - avatar
7 Answers
+ 3
The function logic was all there, you just didn’t assign the value to anything. The second to last line (where you called the function) is doing the same thing as writing “could” on that line. You have to assign that value to a variable (in your case, two). Here is your fixed program: https://code.sololearn.com/WAVQI0lffKDB/?ref=app
11th Jul 2020, 10:15 PM
Jax
Jax - avatar
+ 5
This is what I did... txt = input() #this attaches the user input to the variable txt longest = txt.split() #.split() takes one large string and separates it into a sortable list longest_word = max(longest, key=len) '''This is the tricky part. max() takes the largest values. longest is the split variable of the input. key=len will organize them from smallest to largest. example = [1,22,0000] max(example, key=len) = 0000 as the largest. Alternatively could key=len and take longest[-1] since it was organized from smallest to largest, is largest is at the end of the list. simple doing longest_word = max(longest) from what I can tell takes in longest[0], so doing key=len forces it to actually go through the list fir the largest word''' print(longest_word) #prints the longest word found there, now you did it with just 4 lines of code.
25th Jan 2021, 2:22 AM
Catalyst
+ 4
You should also try to use the appropriate ES6+ modifiers for your variables. Variables that are only assigned once and not changed should be const, others should let (block scope) or var (function scope). Avoid using global variables wherever possible. function longestWord(str) { const one = str.split(" "); let two = ""; for (let three of one) { if (three.length > two.length) two = three; } return two; } const ans = longestWord("the boy who could be king"); console.log(ans);
11th Jul 2020, 10:24 PM
ChaoticDawg
ChaoticDawg - avatar
+ 3
txt = input().split() #your code goes here word = [word for word in txt] letter = [len(letter) for letter in word] place = letter.index(max(letter)) print(txt[place])
26th Jan 2021, 10:54 PM
Ali Kelidari
Ali Kelidari - avatar
+ 2
Jax thanks, wow i didn't really see that. Problem solved, thanks
11th Jul 2020, 10:23 PM
Ibrahim Yusuf
Ibrahim Yusuf - avatar
+ 1
ChaoticDawg thanks, will stick to that. Thanks
11th Jul 2020, 10:29 PM
Ibrahim Yusuf
Ibrahim Yusuf - avatar
+ 1
Catalyst Thanks man, really helpful
25th Jan 2021, 9:14 AM
Ibrahim Yusuf
Ibrahim Yusuf - avatar