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.)