[Python] problems with and or priority and short-circuit logic during leap Calculation

Source: Internet
Author: User

Well, the question is very simple, but some details are quite interesting.


The question is: Determine whether this year is a leap year. If the condition of a leap year is met, the year model 400 is 0, or the model 4 is 0, but the model 100 is not 0.


The answer is:

Import time # calculate whether this year is a leap year. If the condition of the leap year is met, the year model 400 is 0, or the model 4 is 0, but the model 100 is not 0 thisyear = time. localtime () [0] # obtain the year if thisyear % 400 = 0 or thisyear % 4 = 0 and thisyear % 100 <> 0: print 'this year is a leap year' else: print 'this yeat is not a leap year'

The simple source code records some details here.


First, let's review the arrays in Python. Python arrays are divided into three types:
(1) list A common linked list. After initialization, You can dynamically add elements through specific methods.
Definition method: arr = [element]

(2) Tuple Fixed Array. Once defined, the number of elements cannot be changed.
Definition method: arr = (element)

(2) The Dictionary type is a Hash array.
Definition method: arr = {element k: v}


Next let's look at the source code.

The first is the time module. localtime () returns a tuple, which is a fixed-size array. The array contains some data of the current time:

Localtime ([seconds])-> (tm_year, tm_mon, tm_day, tm_hour, tm_min, tm_sec, tm_wday, tm_yday, tm_isdst)


Then, if is used to determine the or and,

There is no "! (Not), & (and), | (OR) ",

These three symbols (completely in English), that is, not, and, or.


But check the source code to determine whether a leap year should be:

1. If it is divisible by 400, It is a leap year.

2. If it can be divisible by 4 and cannot be divisible by 100


Then the if statement should not be:

If thisyear % 400 = 0 or (thisyear % 4 = 0 and thisyear % 100 <> 0 ):

Is that true?


Actually, this is true, but in Python, The and priority is higher than or.


Let's look at a small example:

>>> if 1 or 1 and not 1:...     print 'OK'...OK

If the priority is equal, it should not be output. In fact, the above judgment is equivalent:

if 1 or (1 and not 1):
That is to say,

True or True and not True only indicates (True) or (True and False)



Here we can look at another interesting thing to see the short circuit mechanism in Python:

def a():    print 'this is A!'    return 1def b():    print 'this is B!'    return 1def c():    print 'this is C!'    return 1if a() or b() and not c():    print 'OK!'

If the priority of and is higher than or, shouldn't B be followed by C and then A? How can I output A directly?


In fact, this is also the case in other languages, but I didn't care about it at the time. This is an interesting feature of boolean operators.


Boolean operators have an interesting feature: Evaluate a value only when a value is required.

For example, expression x and y is true only when both variables are true,

Therefore, if x is false, the expression immediately returns false regardless of the value of y (in fact, each language has this feature ).

In fact, if x is false, the expression returns the value of x ---- otherwise, it returns the value of y.

This behavior is called short-circuit logic or lazy evaluaion ):

Boolean operators are generally called logical operators. As you can see, the 2nd values are sometimes "short-circuited ".

This behavior also applies to or.

In expression x or y, if x is true, it returns the value of x directly; otherwise, the value of y is returned.

Note that this means that all code after the Boolean operator will not be executed.



Let's take a look at the example above. The "and" priority is high, indicating that the expressions closest to the two sides are in the relationship with each other. Such a combination is preferred.

Obviously, when the first value is True, there is no need to calculate the value of or. The result is True.



Use and or in Python to implement ternary computation, for example, a function in JS:

function trans(v) {      return (v==0)?1:v;  } 

There are two alternative solutions in Python:

def trans(v):          return 1 if v==0 else v 

Or:

def trans(v):          return v==0 and 1 or v  

Explanations:

If the value of v is equal to 0, and the value of 1 is true, then 1 is directly returned without the following or operation;

If v is equal to 0, it is false, followed by 1. If it is false, or is continued, v is returned.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.