我正在阅读探索算法,这似乎是一本强烈推荐的书。我在看第一个“二进制搜索”算法,这个家伙用两个"ifs“代替一个"if”和"elif“。使用两个“如果”会更好还是更快?
def binary_search(list, item):
low = 0
high = len(list) - 1
while low <= high:
mid = (low + high)
guess = list[mid]
if guess == item:
return mid
if guess > item:
high = mid - 1
else:
low = mid + 1
return None
my_list = [1,3,5,7,9]发布于 2020-05-12 18:31:23
example1
>>> def foo():
a = 10
if a == 10:
print("condition1")
elif a == 10:
print("condition2")
else:
print(0)
>>> foo()
condition1
>>> 当if为true时,elif保证不会运行。
example2
def foo():
a = 10
if a == 10:
print("condition1")
if a == 10:
print("condition2")
else:
print(0)
>>> foo()
condition1
condition2
>>> example3修改example2的if语句。
if a == 10:
print("condition1")
return a输出
>>> foo()
condition1
10因此,在您的示例中,首先添加一个返回,if语句具有类似于if-elif块的类似操作。(返回a)阻止在example3中执行第二个if语句。
发布于 2020-05-12 18:34:34
多重IFs
当您想要完成不同的任务时,可以使用多个ifs,是相互独立的。其中一个任务的执行不会影响其他任务的执行。
让我们看一个例子:
if primeMember:
makeDeliveryFree()
if validDiscountCoupon:
giveDiscount(couponCode)
if customersBirthday:
giveBirthdayDiscount()因此,在上面的例子中,我们要在不同的条件下执行不同的任务,并且任务是相互独立的。免费送货不会以任何方式影响折扣。
对于多个ifs,可以执行所有ifs中的语句;另一方面,也可以不执行if中的任何语句。
如果,ELIF,其他链
另一方面,当我们想要完成一个特定的任务时,我们会使用if,elif,else链,但是我们希望在不同的条件下以不同的方式来完成这个任务。
让我们看一个例子:
if hasBalanceInWallet:
setPaymentMode("wallet")
elif hasCreditCardSaved:
setPaymentMode("credit-card")
else
showPaymentModeSelectorDialog()因此,在上面的示例中,我们试图完成的任务是设置支付模式,我们需要在不同的场景下不同地设置它,但我们只想设置一次(也就是说,我们只希望运行其中一个分支)。
发布于 2020-05-12 20:00:22
正如其他答案所提到的,在执行elif的if之后,return并不是必需的。但他们并没有涵盖演出的影响。我觉得测试会很有趣。
事实证明,使用if/elif/else比单独使用if要快一些。
from timeit import timeit
import random
def count_items_ifelifelse(items, threshold):
below, on, above = 0, 0, 0
for item in items:
if item > threshold:
above += 1
elif item < threshold:
below += 1
else:
on += 1
return below, on, above
def count_items_ififif(items, threshold):
below, on, above = 0, 0, 0
for item in items:
if item > threshold:
above += 1
if item < threshold:
below += 1
if item == threshold:
on += 1
return below, on, above
def generate_items_and_threshold(count=100_000):
"""List of reproducible random numbers to test with. Set threshold at half"""
items = list(range(count))
random.Random(123).shuffle(items)
threshold = count // 2
return items, threshold
def run_test():
t1 = timeit(
"count_items_ifelifelse(i, t)",
setup="from __main__ import count_items_ifelifelse, generate_items_and_threshold; i, t = generate_items_and_threshold()",
number=1000,
)
print("count_items_ifelifelse: {:.2f}".format(t1))
t2 = timeit(
"count_items_ififif(i, t)",
setup="from __main__ import count_items_ififif, generate_items_and_threshold; i, t = generate_items_and_threshold()",
number=1000,
)
print("count_items_ififif: {:.2f}".format(t2))
if __name__ == "__main__":
run_test()此输出(Python3.8.2,Windows):
count_items_ifelifelse: 6.69
count_items_ififif: 8.71大约20%的速度,因为更多不必要的if评估每个循环。它的另一面是,对于if/elif/else,性能将根据数据的排序方式以及是否首先检查最常见的条件而有所不同。
https://stackoverflow.com/questions/61758941
复制相似问题