开发者

Python 3 order of testing undetermined

开发者 https://www.devze.com 2023-02-05 15:31 出处:网络
string=\'a\' p=0 while (p <len(string)) & (string[p]!=\'c\') : p +=1 print (\'the end but theprocessalready died \')
string='a'
p=0
while (p <len(string)) & (string[p]!='c') :
                    p +=1

print ('the end but the  process  already died ')
       while (p <1) & (string[p]!='c') :
IndexError: string index out of range

I want to test a condition up to the end of a string (example string length=1) why are both parts of the and executed is the condition is already false! as long as p < len(s开发者_开发技巧tring). the second part does not even need executing. if it does a lot of performance can be lost


You're not using proper boolean and. Use it and you won't see this problem. What you're using (&) is a bitwise comparison, which evaluates both sides.


Bitwise AND, "a & b", should be thought of as

function _bitwise_and(A,B):
    # A and B are Python expressions
    #   which result in lists of 1's and 0's

    a = A.evaluate()
    b = B.evaluate()

    return [ 1 if abit==1 and bbit==1 else 0 for abit,bbit in zip(a,b)]

so, graphically,

a:   ...  0 1 1 0
b:   ...  1 0 1 0
         --------
a&b  ...  0 0 1 0   <- each bit is 1 if-and-only-if the
                       corresponding input bits are both 1

and the result is a list of bits, packed into an integer.

.

Logical AND, "a and b", should instead be thought of as

function _and(A,B):
    # A and B are Python expressions which result in values having truthiness

    a = A.evaluate()
    if is_truthy(a):
        b = B.evaluate()
        return b
    else:
        return a

.

Notice: if the result of A is falsy, B never gets evaluated - so if expression B has an error when evaluated, bitwise AND will result in an error while logical AND will not.

This is the basis for the common Python idiom,

while (offset in data) and test(data[offset]):
    do_something_to(data[offset])
    next offset

... because data[offset] is only evaluated if offset is a useable (non-error-producing) value.

By using '&' instead of 'and', you guarantee an error by evaluating data[last_offset+1] at the end of your loop.

.

Of course, this could have been avoided with another common idiom:

for ch in string if ch=='c':
    do_something_to(ch)

which avoids IndexError problems altogether.


You need to use the boolean operators and and or rather than the bitwise operators & and |

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号