+ 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);
7 Réponses
+ 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
+ 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.
+ 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);
+ 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])
+ 2
Jax thanks, wow i didn't really see that. Problem solved, thanks
+ 1
ChaoticDawg thanks, will stick to that. Thanks
+ 1
Catalyst Thanks man, really helpful