我们的组织有一个必要的编码规则(没有任何解释):
if ... else如果构造应该用else子句终止
例1:
if ( x < 0 )
{
x = 0;
} /* else not needed */
Run Code Online (Sandbox Code Playgroud)
例2:
if ( x < 0 )
{
x = 0;
}
else if ( y < 0 )
{
x = 3;
}
else /* this else clause is required, even if the */
{ /* programmer expects this will never be reached */
/* no change in value of x */
}
Run Code Online (Sandbox Code Playgroud)
这个设计要处理的边缘情况是什么?
关于其原因的另一个问题是,示例1 …
一时兴起,我最近测试了这两种方法timeit
,看看哪种评估方法更快:
import timeit
"""Test method returns True if either argument is falsey, else False."""
def and_chk((a, b)):
if not (a and b):
return True
return False
def not_or_chk((a, b)):
if not a or not b:
return True
return False
Run Code Online (Sandbox Code Playgroud)
......并得到了这些结果:
VALUES FOR a,b -> 0,0 0,1 1,0 1,1
method
and_chk(a,b) 0.95559 0.98646 0.95138 0.98788
not_or_chk(a,b) 0.96804 1.07323 0.96015 1.05874
...seconds per 1,111,111 cycles.
Run Code Online (Sandbox Code Playgroud)
效率的差异在1%到9%之间,总是有利于if not (a and b)
,这与我的预期相反,因为我理解if not a or not b
它将按顺序评估其术语(if …
python if-statement micro-optimization logical-operators python-2.7
我在youtube上观看Raymond Hettinger的 python 讲座.他展示了退出循环的正确方法:
def find(seq, target):
for i, value in enumerate(seq):
if value == target:
break
else:
return -1
return i
Run Code Online (Sandbox Code Playgroud)
我不明白为什么要烦恼其他声明,而不仅仅是:
def find(seq, target):
for i, value in enumerate(seq):
if value == target:
return i
return -1
Run Code Online (Sandbox Code Playgroud)
我是否遗漏了某些内容,或者出于某种原因有时添加其他/ break语句也是个好主意?
我使用es-lint清理代码中的错误.我遇到过这个错误:
'返回'后不必要的'其他'.(无其他收益)
} else {
Run Code Online (Sandbox Code Playgroud)
返回后我总是使用else语句.有什么我可以忽略的吗?
if (cctot <= 3 && cctot > 0) {
alert('Credit under $3.00 not allowed');
return Number.MIN_SAFE_INTEGER; // important to return 0 so we can check for these conditions for validation
} else {
cctot *= -1;
}
}
return precise(cctot);
}
module.exports = calculateCredit;
Run Code Online (Sandbox Code Playgroud) python ×2
c ×1
ecmascript-6 ×1
if-statement ×1
javascript ×1
jquery ×1
loops ×1
misra ×1
python-2.7 ×1