Python functions (cont.)

Source: Internet
Author: User

First, learn about the bubbling algorithm that was not completed before

Li = [13,22,6,99,11]

From small to large

From the first number, shift the big one backwards.

For M in range (4):

NUM1 = Li[m]

num2 = li[m+1]

If NUM1 > num2:

temp = Li[m]

LI[M] = num2

LI[M+1] = Temp

Print Li

Loop four times and put the maximum number at the end of the list.

For M in range (3):

NUM1 = Li[m]

num2 = li[m+1]

If NUM1 > num2:

temp = Li[m]

LI[M] = num2

LI[M+1] = Temp

And so write the following code

Vim day4-1.py

#!/usr/bin/python
#-*-Coding:utf-8-*-


Li = [13,22,6,99,11]for m in Range (4): #循环num1 = li[m]num2 = Li[m+1]if num1 > num2: #前一个数字和后一个对比如果前面数字大与后面的对调temp = num1l I[M] = num2li[m+1] = tempprint lifor m in range (3): NUM1 = li[m] num2 = li[m+1] if NUM1 > num2: temp = NUM1 li[m] = num2 li[m+1] = tempprint lifor m in range (2): Num1 = li[m] num2 = li[m+1] if NUM1 > Nu M2: temp = num1 li[m] = num2 li[m+1] = tempprint lifor m in range (1): NUM1 = li[m] num2 = li[m+1]< C14/>if num1 > num2: temp = num1 li[m] = num2 li[m+1] = Tempprint li# multiple loops to get sorted results

  

[email protected] scripts]# python day4-1.py
[13, 6, 22, 11, 99]
[6, 13, 11, 22, 99]
[6, 11, 13, 22, 99]
[6, 11, 13, 22, 99]

This kind of loop is cumbersome, if you do not know the length of the list is more troublesome need multiple loops

Vim day4-2.py

#!/usr/bin/python#-*-Coding:utf-8-*-li = [13,22,6,99,11]for N in Range (1,len (LI)-1):            #外层循环1, 2,3,4 for        m in ran GE (Len (li)-n):      #内层循环4, 3,2,1                num1 = li[m]                num2 = li[m+1]                if NUM1 > num2:                        temp = li[m]                        li[m] = l I[M+1]                        li[m+1] = tempprint Li

Run the same as the result

[email protected] scripts]# python day4-2.py
[6, 11, 13, 22, 99]

Python functions (cont.)

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.