1. [顺时针打印二维数组] 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
1 def output_array(matrix): 2 ''' 3 输入一个矩阵,返回一个顺时针打印的列表 4 :param matrix: 矩阵(二维数组) 5 :return: list 6 ''' 7 list = [] 8 while True: 9 try:10 # 顺序打印矩阵第一行11 len_top = len(matrix[0])12 for i in range(len_top):13 list.append(matrix[0].pop(0))14 matrix.pop(0) # ①第一行的元素已经pop完了,但是此时matrix[0] = []而非none,所以这里得pop一下15 16 # 依次打印最右边的一列(每一行的最后一个元素)17 len_right = len(matrix)18 for j in range(len_right):19 list.append(matrix[j].pop(-1))20 21 # 倒序打印最下面一行22 len_bottom = len(matrix[0])23 for k in range(len_bottom):24 list.append(matrix[-1].pop(-1))25 matrix.pop(-1) # 同①26 27 # 倒序打印最左边的一行(倒序打印每一行的第一个元素)28 len_left = len(matrix)29 for l in range(len_left):30 list.append(matrix[-l-1].pop(0))31 32 except BaseException: # 这是个比较懒的方法,没有设置跳出条件,只有触发list out of range 来跳出循环33 return list34 35 # --------测试用例------------------36 if __name__ == '__main__':37 a = [[1,2,3],[4,5,6],[7,8,9],[10,11,12],[13,14,15],[16,17,18]] # 小奇数*大偶数38 b = [[1,2,3,4,5,6],[7,8,9,10,11,12],[13,14,15,16,17,18]] # 大奇数*小偶数39 c = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]] # 偶数*偶数40 d = [[1,2,3],[4,5,6],[7,8,9]] # 奇数*奇数41 e = [[1,2],[3,4],[5,6]] # 小偶数*大奇数42 f = [[1,2,3,4]] # 大偶数*小奇数43 for i in [a,b,c,d,e,f]:44 print(output_array(i))
输出:
1 /Users/***/anaconda3/bin/python /Users/***/Documents/project/0911/面试/牛客编程/顺时针打印矩阵.py2 [1, 2, 3, 6, 9, 12, 15, 18, 17, 16, 13, 10, 7, 4, 5, 8, 11, 14]3 [1, 2, 3, 4, 5, 6, 12, 18, 17, 16, 15, 14, 13, 7, 8, 9, 10, 11]4 [1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10]5 [1, 2, 3, 6, 9, 8, 7, 4, 5]6 [1, 2, 4, 6, 5, 3]7 [1, 2, 3, 4]9 Process finished with exit code 0
2. [快速排序] 输入一个无序列表,然后返回从小到大排序的列表
1 #-*- coding:utf-8 -*- 2 #Author: Bing Xu 3 4 def quick_sort(list,start,end): 5 6 if start >= end: 7 return list 8 9 low = start10 high = end11 mid = list[start]12 13 while low < high:14 while low < high and list[high] >= mid:15 high -= 116 list[low] = list[high]17 while low < high and list[low] < mid:18 low += 119 list[high] = list[low]20 list[low] = mid21 quick_sort(list,start,low-1)22 quick_sort(list,low+1,end)23 return list24 25 #------------- 测试 ---------------26 if __name__ == '__main__':27 a = [1,2,6,5,3]28 b = []29 # c = [-1,1,3,'l']30 # e = [1+2j,1,2] 暂不支持比较字符和复数,明天再想办法解决31 for i in [a,b]:32 print(quick_sort(i,0,len(i)-1))
输出:
1 [1, 2, 3, 5, 6]2 []3 4 Process finished with exit code 0