Python Practice Example 37

Python 100例Python 100 Examples

Problem:Sort 10 numbers.

Program analysis:You can use the selection method, that is, in the comparison with the remaining 9 elements, select the smallest one and swap it with the first element; then similarly, use the second element to compare with the remaining 8 elements and swap.

Program source code:

Example

#!/usr/bin/python # -*- coding: UTF-8 -*- if __name__ == "__main__": N = 10 # input data print ('Please enter 10 numbers:\n') l = [] for i in range(N): l.append(int(input('Enter a number:\n'))) print for i in range(N): print (l[i]) print # Sort 10 numbers for i in range(N - 1): min = i for j in range(i + 1,N): if l[min] > l[j]:min = j l[i],l[min] = l[min],l[i] print ('After sorting:') for i in range(N): print (l[i])

The output of the above example is:

请输入10个数字:

输入一个数字:
5
输入一个数字:
3
输入一个数字:
23
输入一个数字:
67
输入一个数字:
2
输入一个数字:
56
输入一个数字:
45
输入一个数字:
98
输入一个数字:
239
输入一个数字:
9

5
3
23
67
2
56
45
98
239
9

排列之后:
2
3
5
9
23
45
56
67
98
239

Python 100例Python 100 Examples

Other extensions