首页 > 解决方案 > Does it make any difference if we change the position of operands in a logical statement?

问题描述

I wrote the following function in python which returns a sublist (i.e. the part of the list that it had been iterating through until it finds a particular value (in my case 5) without including it in the sublist and also stops iterating further).

def sublist(a):
    b=[]
    i=0
    while(a[i]!=5 and i<=len(a)-1):
        b.append(a[i])
        i=i+1
    return b

the above function worked fine with all test cases except this one a=[1, 6, 2, 3, 9]. It gave the following error: IndexError: list index out of range.

But when I interchanged the operands of the while loop condition and wrote the same code in the following way I got output for all the test cases:

def sublist(a):
    b=[]
    i=0
    while(i<=len(a)-1 and a[i]!=5):
        b.append(a[i])
        i=i+1
    return b

Why didn't I get output in the first case?

标签: pythonpython-3.x

解决方案


这被称为“逻辑短路”,当一个逻辑表达式必须被评估时,编程语言观察第一个操作数并说:“这是一个 OR,如果第一个操作数对我来说没问题,那么整个表达式也没问题!” 所以它忽略了第二个。

对于 AND 是一样的,但是:“这是一个 AND,如果第一个操作数没问题,我必须检查第二个,否则整个表达式不正确”

在这种情况下,您首先检查 a[i]

可能

抛出异常,然后为 i<=len(a)-1。

我做了一点ELI5。

编辑:我忘了如果你不使用括号也看这个表https://en.wikipedia.org/wiki/Logical_connective#Order_of_precedence

同样作为一名计算机科学家,您必须对短路有很好的了解,它可以帮助您进行很多表演


推荐阅读