我正在努力解决以下问题:
编写一个函数has23(nums),它取一个长度为2的int列表,如果它包含True
或2
,则返回3
。 < / p>
mycode的:
def has23(nums):
for i in nums:
if i == 2 or i == 3:
return True
return False
测试:
has23([2, 5])
预期:True
得到:True
has23([42, 53])
预期:False
得到:False
has23([4, 3])
预期:True
得到:**False**
has23([1, 2])
预期:True
得到:**False**
我不知道为什么它会返回False
给我,在最后两次测试中它应该是True
。
答案 0 :(得分:0)
缩进很重要。您只需迭代一次,因为return False
出现在您的循环中,导致它提前退出。将其更改为:
def has23(nums):
for i in nums:
if i == 2 or i == 3:
return True
return False
正如@dawg所说,你不需要循环。
def has23(nums):
return 2 in nums or 3 in nums
// Python interpreter courtesy of http://www.skulpt.org/
// of which I have no affiliation
function outf(text) {
var mypre = document.getElementById("output");
mypre.innerHTML = mypre.innerHTML + text;
}
function builtinRead(x) {
if (Sk.builtinFiles === undefined || Sk.builtinFiles["files"][x] === undefined)
throw "File not found: '" + x + "'";
return Sk.builtinFiles["files"][x];
}
function runit() {
var prog = document.getElementById("yourcode").value;
var mypre = document.getElementById("output");
mypre.innerHTML = '';
Sk.canvas = "mycanvas";
Sk.pre = "output";
Sk.configure({
output: outf,
read: builtinRead
});
try {
eval(Sk.importMainWithBody("<stdin>", false, prog));
} catch (e) {
alert(e.toString())
}
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="https://raw.githubusercontent.com/skulpt/skulpt-dist/master/skulpt.min.js" type="text/javascript"></script>
<script src= "https://raw.githubusercontent.com/skulpt/skulpt-dist/master/skulpt-stdlib.js" type="text/javascript"></script>
<form style='float:left; margin: 5px'>
<textarea cols="40" id="yourcode" rows="10">def has23(nums):
return 2 in nums or 3 in nums
print(has23([2, 5]))
print(has23([42, 53]))
print(has23([4, 3]))
print(has23([1, 2]))
</textarea><br>
<button onclick="runit()" type="button">Run</button>
</form>
<pre id="output"></pre>
&#13;