Python Code optimization Case study

Source: Internet
Author: User

First edition Example:

def displaynumtype (num): Print num, "is", if Type (num) ==type (0): print ' An Interger ' elif type (num) ==type (0  L): print ' A long ' elif type (num) ==type (0.0): print ' A float ' elif type (num) ==type (0+0j): Print ' A complex number ' else:print ' not a number at all!! '

Final Version Example:

def displaynumtype (num): Print num, ' is ', if Isinstance (num, (Int,long,float,complex)): print ' A number of Typ E: ', type (num). __name__ else:print ' not a number at all!! '


Optimization ideas:

1. Reduce the number of function calls

In the first version of the code, the two-time type () is called each time it is judged.

    • Optimization method:

Import typesif type (num) ==types. Inttype ...


2. Compare object value VS object identity

The type (0), type (42), and so on are the same object "<type ' Int ' >", and there is no need to compare it. Because each type has only one type of object.

    • Optimization method:

If Type (num) is types. Inttype. # #or Type (0)


3. Reduce the number of queries

In order to get the object type of an integer, the interpreter had to find the name of the types module first, and then find the inttype in the dictionary of the module.

By using From-import, you can reduce the query one time.

    • Optimization method:

From types import inttypeif type (num) is Inttype


4. Conventions and code styles

The Isinstance () function makes the IF statement more convenient and more readable.

    • Optimization method:

If Isinstance (num,int) ...


Selected from "Python Core programming (second Edition)", chapter fourth P68

Python Code optimization Case study

Related Article

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.