我目前正在使用python进行任务,我需要帮助,我是
编写一个名为longest的函数,它将采用一串空格分隔的单词并返回最长的单词。
例如:
longest("This is Andela") => "Andela"
longest("A") => "A"
这是样本测试
const assert = require("chai").assert;
describe("Module 10 - Algorithyms", () => {
describe("longest('This Is Andela')", () => {
let result = longest("This Is Andela");
it("Should return 'Andela'", () => {
assert.equal(result, 'Andela');
});
});
describe("longest('This')", () => {
let result = longest("This");
it("Should return 'This'", () => {
assert.equal(result, 'This');
});
});
describe("longest(23)", () => {
let result = longest(23);
it("Should return ''", () => {
assert.equal(result, '');
});
});
});
这就是我试过的
function longest(str) {
str = "This is Andela";
var words = str.split(' ');
var longest = '';
for (var i = 0; i < words.length; i++) {
if (words[i].length > longest.length) {
longest = words[i];
}
}
return longest;
}
但是我的代码似乎只传递了第一个测试用例。请考虑我是javascript的新手,我需要更改以传递另外两个案例
答案 0 :(得分:9)
您需要在函数中删除此行:
str = "This is Andela";
你的功能应该是(添加检查str是否是字符串):
function longest(str) {
if(typeof str !== 'string') return '';
var words = str.split(' ');
var longest = '';
for (var i = 0; i < words.length; i++) {
if (words[i].length > longest.length) {
longest = words[i];
}
}
return longest;
}
答案 1 :(得分:2)
没有数组且没有每个语句的简化代码。
function longer(champ, contender) {
return (contender.length > champ.length) ? contender: champ;
}
function longestWord(str) {
var words = str.split(' ');
return words.reduce(longer);
}
console.log(longestWord('This is longest'));
console.log(longestWord('This is longest or may this is more longestest'));
答案 2 :(得分:0)
检查一下:
function longest(s){
return typeof s != 'string' ? '' : s.split(' ').sort( (a,b) => b.length - a.length)[0]
}
通过串联将输入转换为字符串,并使用空字符串,以便在传递数字时也能正常工作。