Python Learning Journey-Basic (vii) reflection, bubble sorting algorithm

Source: Internet
Author: User

This article highlights:Bubble algorithm Reflection one, bubble sort
    1. Compares the adjacent elements. If the first one is bigger than the second one, swap them both.
    2. Do the same for each pair of adjacent elements, starting with the last pair from the first pair to the end. When this is done, the final element will be the maximum number.
    3. Repeat the above steps for all elements, except for the last one.
    4. Repeat the above steps each time for fewer elements, until there are no pairs of numbers to compare.
code example:
Li = [5, 2, 8, 5, p, 6, 98,]times = Len (li) for I in Range (times): for    J in Range (times-1):        if LI[J] > LI[J+1]:            li[j], li[j+1] = li[j+1], Li[j]print (LI) Results: [2, 5, 5, 6, 8, 19, 33, 67, 98]
# # # Insert Sort, select sort two, reflection sometimes we want to import a method of a module, or we need to assign a value to a parameter of an object, which needs to be entered in the form of a parameter pass string. What kind of solution would you choose to solve in such a situation? For example:
# module Commons.pydef Home ():    print ("Main Page") def login ():    print ("Login page") def logout ():    print ("Exit page") # index.py Importing module Import Commons def run ():    INP = input ("Please enter the URL to access:")    if InP = = "Home":        commons.home ()    elif InP = = "Lo Gin ":        commons.login ()    elif INP = =" Logout ":        commons.logout ()    else:        print (" 404 ") if __name__ = = ' __main__ ':    

If you use the IF statement in the code above, you have to have a elif statement for each method you write, and if there are 1000 methods, there are 1000 elif statements. This is a weak explosion. Is there a simpler way to implement string arguments into function names? That will be used to reflect. The modified code is as follows:
# module Commons.pydef Home ():    print ("Main Page") def login ():    print ("Login page") def logout ():    print ("Exit page") # index.py Importing module Import Commons def run ():    INP = input ("Please enter the URL to access:")  # String Type    # manipulate (check, find, modify, delete) Members    in the form of a string to the object (module) # delattr (), setattr ()  operation in memory    # by HASATTR () to determine if the function exists if    hasattr (Commons, INP):        # Perform functions in the Commons module by reflection        func = GetAttr (commons, INP)        func ()    else:        print ("404") if __name__ = = ' __main __ ':    run ()
Now there is only one module, if there are 1000 modules, do you want to import 1000 times? Of course not, we introduce the __import__ () function to implement string conversion into module introduction. The code is as follows:
# module Account.pydef login ():    print ("Login page") def logout ():    print ("Exit page") # Module Commons.pydef Home ():    Print (Main page ") # module Manager.pydef order ():    Print (" Order Page ") # Main function index.py import module def run ():    # account/login format    INP = input (" Please enter Access URL: ")    m, f = inp.split ("/")  # Account/login format is split into two parts m=" account ", f=" login "  m,f are string    obj = __ Import__ (M)  # Importing a module with the name account        # to implement a call to a function in a module by reflection    if hasattr (obj, f):        func = getattr (obj, f)        Func ()    else:        print ("404") if __name__ = = ' __main__ ':    run ()
The above example is actually a forgery of the web framework of the routing system. Add:
__import__ ("libs.aaa.bbb", Fromlist=true)   # Support for directory stitching, otherwise you can only import Libs
If the complete package wants to achieve higher portability, it is necessary to put the file's home directory in Sys.path to facilitate the module's import, as follows:
Def add_path ():    # Add program's execution path    import OS    import sys    # ps.path.abspath (__file__) Gets the absolute path of the currently executing file    # Os.path.dirname () Gets the previous layer path of the current path    sys.path.append (Os.path.dirname (Os.path.dirname (Os.path.abspath))) # until the home directory is found, and then add the home directory to Sys.path # __name__ only when the current file is executed again, __name__ =__main__, the import does not execute if __name__ = = ' __main__ ':    Add_path ()

Python Learning Journey-Basic (vii) reflection, bubble sorting algorithm

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.