Python Exercise Example 39

Python 100例Python 100 Examples

Problem:There is an already sorted array. Now input a number, and insert it into the array according to the original rule.

Program analysis:First determine whether this number is greater than the last number, then consider inserting it in the middle; after insertion, the numbers after this element are shifted back one position in turn.

Program source code:

Example (Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- if __name__ == '__main__': # Method 1: 0 serves as a placeholder for the inserted number a = [1,4,6,9,13,16,19,28,40,100,0] print ('Original list:') for i in range(len(a)): print (a[i]) number = int(input("\nInsert a number:\n")) end = a[9] if number > end: a[10] = number else: for i in range(10): if a[i] > number: temp1 = a[i] a[i] = number for j in range(i + 1,11): temp2 = a[j] a[j] = temp1 temp1 = temp2 break print ('List after sorting:') for i in range(11): print (a[i])

The output result of the above example is:

原始列表:
1
4
6
9
13
16
19
28
40
100
0

插入一个数字:
7
排序后列表:
1
4
6
7
9
13
16
19
28
40
100

Python 100例Python 100 Examples

Other extensions